public List LoadExcelSheet(
string excelFile, string sheetName)
{
List dataList = new List();
/// load excel file as an ole database
OleDbConnection excelDatabase =
new OleDbConnection(string.Format(
"Provider = Microsoft.Jet.OLEDB.4.0;" +
"Data Source = {0};" +
"Extended Properties='Excel 8.0;HDR=No'",
excelFile));
excelDatabase.Open();
/// query sheet from excel file
OleDbDataAdapter sheetAdapter =
new OleDbDataAdapter(string.Format(
"SELECT * FROM [{0}]", sheetName),
excelDatabase);
DataTable fileData = new DataTable();
sheetAdapter.Fill(fileData);
/// scan all cells in the sheet
foreach (DataRow row in fileData.Rows)
{
foreach (object item in row.ItemArray)
{
if (!(item is DBNull) )
{
dataList.Add(item.ToString());
}
}
}
/// close and release database connection
excelDatabase.Close();
return dataList;
}
這裡值得注意的是,如果試算表中有些欄位是空的
讀出來的資料會是
另外,如果是手動輸入試算表名稱的話
要記得在試算表名稱後面加一個$,例如預設的"Sheet1$"
--
參考資料
轉錄 C# 讀取 Excel
C# 讀取 Excel
DataTable 類別
沒有留言:
張貼留言