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";
  • 相关阅读:
    HTML学习笔记2
    HTML的学习笔记
    Unsupported major.minor version 51.0解决办法
    java出现The type java.lang.Object cannot be resolved. It is indirectly referenced.....解决办法
    切片
    switch语句
    if-else语句与for循环
    闭包函数
    函数
    常量
  • 原文地址:https://www.cnblogs.com/huhangfei/p/4991965.html
Copyright © 2011-2022 走看看