当前位置: 编程技术>.net/c#/asp.net
将excel数据转换成dataset示例
来源: 互联网 发布时间:2014-10-28
本文导语: 代码如下:/// /// EXCEL数据转换DataSet /// /// 文件全路径 /// 表名 /// private DataSet GetDataSet(string fileName) { string strConn = "Provider=Mic...
代码如下:
///
/// EXCEL数据转换DataSet
///
/// 文件全路径
/// 表名
///
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 List = new List { "收款金额", "代付关税", "垫付费用", "超期", "到账利润" };
List List = new List { };
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();
}
}