读取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";