C#讀取excel--OLEDB方式
阿新 • • 發佈:2018-12-29
這裡貼的程式碼是讀取本地檔案系統中的excel
//讀取EXCEL的方法 (用範圍區域讀取資料)
private static DataTable GetExcelTableByOleDB(string excelFilePath)
{
//Excel連線
OleDbConnection conn = null;
DataTable dataTable = null;
try
{
//資料表
DataSet ds = new DataSet();
//獲取副檔名
string extension = System.IO.Path.GetExtension(excelFilePath);
string fileName = System.IO.Path.GetfileName(excelFilePath);
switch (extension)
{
//HDR=YES,略過第一行資料;IMEX=1,只讀方式開啟
case ".xls":
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFilePath + ";" + "Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"");
break;
case ".xlsx":
conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1;\"");
break;
default:
conn = null;
break;
}
if (conn == null)
{
return null;
}
conn.Open();
//獲取Excel中所有Sheet表的資訊
System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
//獲取Excel的第一個Sheet表名
string tableName = schemaTable.Rows[0][2].ToString().Trim();
string strSql = "select * from [" + tableName + "]";
//獲取Excel指定Sheet表中的資訊
OleDbCommand objCmd = new OleDbCommand(strSql, conn);
OleDbDataAdapter myData = new OleDbDataAdapter(strSql, conn);
myData.Fill(ds, tableName);//填充資料
//dataTable即為excel檔案中指定表中儲存的資訊
dataTable = ds.Tables[tableName];
}
catch(Exception e){
ExceptionHelper.throwException(e, "解析excel檔案出錯");
}
finally
{
if (conn != null) { conn.Close(); }
}
return dataTable;
}