//Excel导入
public DataTable ExcelImportTotImportSequenceNo(string filePath, string ExtensionName)
{
OleDbConnection olecon = null;
OleDbDataAdapter oleda = null;
string con = "";
try
{
if (ExtensionName == ".xls")
con = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;IMEX=1'";
else
con = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
olecon = new OleDbConnection(con);
olecon.Open();
//返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等
DataTable dtSheetName = olecon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
oleda = new OleDbDataAdapter(string.Format("select * from [Sheet1$]"), olecon);
DataTable dt = new DataTable();
oleda.Fill(dt);
//对列名 进行空格处理
for (int i = 0; i < dt.Columns.Count; i++)
{
dt.Columns[i].ColumnName = dt.Columns[i].ColumnName.Trim();
}
return dt;
}
catch (Exception ex)
{
oleda.Dispose();
olecon.Dispose();
olecon.Close();
throw ex;
}
finally
{
oleda.Dispose();
olecon.Dispose();
olecon.Close();
}
[Sheet1$] 这个名字为Excel内的表名
Excel导入方法详解
本文详细介绍了使用OleDbConnection和OleDbDataAdapter从.xls和.xlsx文件中导入数据到DataTable的方法,包括如何获取Excel架构、填充DataTable以及处理列名。
661

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



