#region 从Excel读入数据到DataSet
public static DataSet ExcelToDataSet(string strFilePath,string type)
{
string strConn="";
if (type == "excel2003")
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
}
else if (type == "excel2007")
{
strConn = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + strFilePath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";
}
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });//获得Excel中的所有sheetname
OleDbDataAdapter odda;
DataSet ds = new DataSet();
foreach (DataRow dr in sheetNames.Rows)
{
DataSet dsOne = new DataSet();
odda = new OleDbDataAdapter("select * from [" + dr[2] + "]", strConn);//dr[2] is sheetname
odda.Fill(dsOne);
if (dsOne.Tables.Count > 0)
{
DataTable dt = dsOne.Tables[0].Copy();
dt.TableName = dr[2].ToString();
ds.Tables.Add(dt);
}
}
conn.Close();
return ds;
}
#endregion c# Excel转入到DataSet
最新推荐文章于 2024-02-29 13:56:29 发布
本文介绍了一种将Excel文件读取并转换为DataSet的方法。通过判断Excel版本选择不同的连接字符串,使用OleDb连接到Excel,获取所有工作表名称,并将每个工作表的数据填充到单独的DataTable中,最后将这些表集合到一个DataSet里。
832

被折叠的 条评论
为什么被折叠?



