先读取Excel文件并存到dataset
public DataSet ExcelToDataTable(string filename, string strsheetname)
{
try
{
//源的定义
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filename + ";" + "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';"; //Sql语句
string strExcel = string.Format("select * from [{0}$]", strsheetname);
//string strExcel = "select * from [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];
return ds;
}
catch (Exception err)
{
throw new Exception("数据绑定Excel失败!失败原因:" + err.Message); }
}
然后绑定:
string fileName = fileUpload.PostedFile.FileName;
DataSet ds = ExcelToDataTable(fileName, "sheet1"); rptTab.DataSource = ds.Tables[];
rptTab.DataBind();
需要注意的是 连接字符串中
HDR = Yes 意思是把读取数据的第一行作为数据字段绑定,默认就是YES 不需要的可以把这个设置为NO