1. 首页
  2. 编程语言
  3. C#
  4. 上传并读取EXCEL的数据,显示到GridView中

上传并读取EXCEL的数据,显示到GridView中

上传者: 2018-12-07 07:01:52上传 RAR文件 3.8KB 热度 63次
使用C#上传并读取EXCEL的数据,显示到GridView中,参考附件,简单片段如下: if (extension == ".xls") { //IMEX=1表示将所有的列全部视为文本。省略时,excel中包含 汉字 和 数字,数字会读取不出来。 //HDR表示是否要出现一行标题头。 HDR="YES" 表示把exce中的第一行作为数据的标题。 strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=\"Excel 8.0;IMEX=1;HDR=No\";";//这是excel2003的写法 } else { strConn = "Provider=Microsoft.ace.oledb.12.0;Data Source=" + filepath + ";Extended Properties=\"Exc el 12.0;HDR=No;IMEX=1\";"; //这是excel2007的写法 } try { OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); //获取所有工作薄集合 System.Data.DataTable sTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null); string sheetName = string.Empty; List siteCodes = new List (); string currentSiteCode = string.Empty; if (sTable.Rows.Count > 0) { foreach (DataRow row in sTable.Rows)//循环读取工作薄找到符合列数条件的工作薄内容 { sheetName = row[2].ToString().Trim(); OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetName + "]", strConn); DataSet ds = new DataSet(); oada.Fill(ds); this.gdBoms.DataSource = ds.Tables[0]; this.gdBoms.DataBind(); } } else { this.lblStatus.Text = "请先上传有效的文件"; } conn.Close();
下载地址
用户评论
Raincchina 2018-12-07 07:01:52

不错,非常有用