zoukankan      html  css  js  c++  java
  • 读取Excel数据绑定到Gridview进行显示

    读取Excel数据绑定到Gridview进行显示示例代码。

    读取excel代码

    /// <summary>
            /// 读取Excel
            /// authon:codeo.cn
            /// </summary>
            /// <param name="strExcelFileName"></param>
            /// <param name="strSheetName"></param>
            /// <returns>DataTable</returns>
            public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
            {
                //源的定义
                string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
    
                //Sql语句
                //string strExcel = string.Format("select * from [{0}$]", strSheetName); 这是一种方法
                string strExcel = "select * from  [" + strSheetName + "$]";//[sheet1$]
    
                //定义存放的数据表
                DataSet ds = new DataSet();
    
                //连接数据源
                OleDbConnection conn = new OleDbConnection(strConn);
    
                conn.Open();
    
                //适配到数据源
                OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
                adapter.Fill(ds, strSheetName);
    
                conn.Close();
    
                return ds.Tables[strSheetName];
            }

    GridView绑定daTable数据

     protected void Page_Load(object sender, EventArgs e)
            {
                string path = GetRootPath();
                DataTable daTable = ExcelToDataTable(path + "Content\demo.xlsx", "Sheet1");
                GridView1.DataSource = daTable;
                GridView1.DataBind();
            }

    asp.net取得网站根目录的物理路径

    /// <summary>
            /// 取得网站根目录的物理路径
            /// authon:codeo.cn
            /// </summary>
            /// <returns></returns>
            public static string GetRootPath()
            {
                string AppPath = "";
                HttpContext HttpCurrent = HttpContext.Current;
                if (HttpCurrent != null)
                {
                    AppPath = HttpCurrent.Server.MapPath("~");
                }
                else
                {
                    AppPath = AppDomain.CurrentDomain.BaseDirectory;
                    if (Regex.Match(AppPath, @"\$", RegexOptions.Compiled).Success)
                        AppPath = AppPath.Substring(0, AppPath.Length - 1);
                }
                return AppPath;
            }

    补充

    如何修改表头信息?
    只需在绑定数据前将datatable的列名修改。

    daTable.Columns[0].ColumnName = "表头1";
    daTable.Columns[2].ColumnName = "表头2";
    daTable.Columns[3].ColumnName = "表头3";
  • 相关阅读:
    流量控制--2.传统的流量控制元素
    流量控制--1.概览
    Opentelemetry Collector的配置和使用
    高德全链路压测——精准控压的建设实践
    高德全链路压测——语料智能化演进之路
    业内首发车道级导航背后——详解高精定位技术演进与场景应用
    浅析云控平台画面传输的视频流方案
    关于卫星定位,你想知道的一切
    Pod容器中安装软件包
    面试应该怎么问问题?
  • 原文地址:https://www.cnblogs.com/huhangfei/p/4991965.html
Copyright © 2011-2022 走看看