專案常需匯入 Excel 資料,本文示範如何在 ASP.NET (含 SharePoint 環境) 中上傳 .xls/.xlsx 檔案,透過 OLEDB 讀取工作表資料並轉為 DataTable,同時處理檔案儲存、副檔名驗證與例外捕捉。
OleDbConnection 讀取資料並填入 DataSet,回傳 DataTable。private DataTable ExcelDataSource(string filePath, string sheetName)
{
// 支援 .xls 與 .xlsx 的連接字串
string connStr = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath};Extended Properties='Excel 12.0;HDR=YES;IMEX=1;'";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
string sql = $"SELECT * FROM [{sheetName}]";
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
}
private string[] ExcelSheetName(string filePath)
{
string connStr = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath};Extended Properties='Excel 12.0;HDR=YES;IMEX=1;'";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
DataTable schema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
return schema.Rows.Cast<DataRow>().Select(r => r["TABLE_NAME"].ToString()).ToArray();
}
}
protected void BtnOK_Click(object sender, EventArgs e)
{
if (!BaseInfoTemplateFile.HasFile) return;
string ext = Path.GetExtension(BaseInfoTemplateFile.FileName).ToLower();
if (ext != ".xls" && ext != ".xlsx")
{
ShowAlert("請上傳 .xls 或 .xlsx 檔案");
return;
}
string folder = Server.MapPath($"~/_layouts/15/images/{GetUserFolder()}Upfile/");
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
string savePath = Path.Combine(folder, BaseInfoTemplateFile.FileName);
BaseInfoTemplateFile.SaveAs(savePath);
try
{
string sheet = ExcelSheetName(savePath)[0];
DataTable dt = ExcelDataSource(savePath, sheet);
if (dt != null)
{
foreach (DataRow row in dt.Rows)
{
// 處理每一列資料,如寫入資料庫、建立物件等
}
}
}
catch (Exception ex)
{
ShowAlert("Excel 讀取失敗:" + ex.Message);
}
}
SqlBulkCopy 或 EPPlus、NPOI 等不需安裝驅動程式的純 .NET 函式庫。