首页 > 技术文章 > c#导入excel 绑定数据 repeat为例子

mandalaluo 2014-07-10 09:53 原文

先读取Excel文件并存到dataset 

 1 public DataSet ExcelToDataTable(string filename, string strsheetname)
 2     {
 3         try
 4         {
 5             //源的定义
 6             string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filename + ";" + "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";
 7 
 8             //Sql语句
 9             string strExcel = string.Format("select * from [{0}$]", strsheetname);
10             //string strExcel = "select * from   [sheet1$]";
11 
12             //定义存放的数据表
13             DataSet ds = new DataSet();
14 
15             //连接数据源
16             OleDbConnection conn = new OleDbConnection(strConn);
17 
18             conn.Open();
19 
20             //适配到数据源
21             OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
22             adapter.Fill(ds, strsheetname);
23 
24             conn.Close();
25 
26             //return ds.Tables[strsheetname];
27             return ds;
28         }
29         catch (Exception err)
30         {
31             throw new Exception("数据绑定Excel失败!失败原因:" + err.Message);
32 
33         }  
34     }

然后绑定:

1 string fileName = fileUpload.PostedFile.FileName;
2 DataSet ds = ExcelToDataTable(fileName, "sheet1");
3 
4 
5 rptTab.DataSource = ds.Tables[0];
6 rptTab.DataBind();

需要注意的是    连接字符串中 

HDR =  Yes  意思是把读取数据的第一行作为数据字段绑定,默认就是YES  不需要的可以把这个设置为NO

推荐阅读