将excel数据转换成dataset示例
程序员文章站
2024-02-24 12:36:58
复制代码 代码如下:/// /// excel数据转换d...
复制代码 代码如下:
/// <summary>
/// excel数据转换dataset
/// </summary>
/// <param name="filepath">文件全路径</param>
/// <param name="search">表名</param>
/// <returns></returns>
private dataset getdataset(string filename)
{
string strconn = "provider=microsoft.ace.oledb.12.0;data source=" + filename + ";extended properties='excel 12.0;hdr=yes;imex=1';";
oledbconnection objconn = null;
objconn = new oledbconnection(strconn);
objconn.open();
dataset ds = new dataset();
//list<string> list = new list<string> { "收款金额", "代付关税", "垫付费用", "超期", "到账利润" };
list<string> list = new list<string> { };
datatable dtsheetname = objconn.getoledbschematable(oledbschemaguid.tables, new object[] { null, null, null, "table" });
foreach (datarow dr in dtsheetname.rows)
{
if (dr["table_name"].tostring().contains("$") && !dr[2].tostring().endswith("$"))
{
continue;
}
string s = dr["table_name"].tostring();
list.add(s);
}
try
{
for (int i = 0; i < list.count; i++)
{
ds.tables.add(list[i]);
string sheetname = list[i];
string strsql = "select * from [" + sheetname + "]";
oledbdataadapter odbccsvdataadapter = new oledbdataadapter(strsql, objconn);
datatable dt = ds.tables[i];
odbccsvdataadapter.fill(dt);
}
return ds;
}
catch (exception ex)
{
return null;
}
finally
{
objconn.close();
objconn.dispose();
}
}