使用 C# 與 IronXL 在 ASP.NET MVC 中讀取 Excel 檔案
IronXL 讓 ASP.NET MVC 開發人員能夠直接在 C# 中讀取 Excel 檔案,無需依賴 Microsoft Office,並將 Excel 資料轉換為 System.Data.DataTable,僅需幾行程式碼即可輕鬆在網頁檢視中顯示。
快速入門:在 MVC 中載入並將 Excel 試算表轉換為 DataTable
此範例展示如何在數秒內快速上手:載入 Excel 工作簿、選取其第一個工作表,並使用 IronXL 将其轉換為 System.Data.DataTable —— 無需 Interop,輕鬆無負擔。
簡化工作流程(5 個步驟)
- 安裝 C# 函式庫以在 ASP.NET 中讀取 Excel 檔案
- 在 Excel 檔案中載入並開啟目標工作表
- 存取
ToDataTable方法並將其傳回View - 使用迴圈在網頁上顯示 Excel 資料
- 遍歷所有資料並建立 HTML 表格
如何建立用於讀取 Excel 的 ASP.NET 專案?
為什麼 Visual Studio 2022 最適合用於此任務?
使用 Visual Studio 2022 建立一個新的 ASP.NET 專案。 Visual Studio 2022 針對 .NET Framework 6+ 框架提供卓越的支援,針對 IronXL 方法的 IntelliSense 功能已獲得強化,並在處理大型 Excel 檔案時展現更佳的效能。 此 IDE 的 NuGet 整合功能,讓安裝 IronXL 變得格外簡單。
我應該選擇哪種專案範本?
若要在 ASP.NET 中讀取 Excel 檔案,請選擇"ASP.NET Core Web App (Model-View-Controller)"範本。 此範本提供簡潔的 MVC 結構,將資料處理(讀取 Excel)與呈現邏輯分開。 MVC 模式與 IronXL 的 DataTable 轉換功能完美配合,讓您能夠在控制器中載入試算表,並在檢視中無縫顯示。
建議使用哪個 .NET 版本?
IronXL 適用於 .NET Framework 4.6.2 及以上版本,以及 .NET Core 3.1 及以上版本。 針對新的 ASP.NET MVC 專案,請使用 .NET 6.0 或更高版本以獲得最佳效能與安全性。 這些版本在處理大型 Excel 檔案時提供了更完善的記憶體管理,並針對電子表格檔案格式的轉換,提供了更完善的 async/await 支援。
如何安裝 IronXL 程式庫?
安裝需求為何?
哪種安裝方式最快?
建立新專案後,請安裝 IronXL 函式庫。 請按照以下步驟安裝 IronXL。 開啟 NuGet 套件管理員控制台並執行以下指令:
Install-Package IronXl.Excel
如何驗證安裝是否成功?
若要驗證 IronXL 是否已正確安裝,請在"解決方案資源管理員"中檢查您的專案依賴項。 您應能在"依賴項 > 套件"下看到"IronXL"。 此外,請嘗試在控制器檔案頂端加入 using IronXL; —— IntelliSense 應能立即識別該命名空間。 如需解決安裝問題,請參閱授權指南。
如何在控制器中讀取 Excel 檔案?
控制器動作中應包含哪些程式碼?
開啟您的 ASP.NET 專案中的預設控制器(例如 HomeController.cs),並將 Index 方法替換為以下程式碼:
using IronXL;
using System.Data;
public ActionResult Index()
{
// Load the Excel workbook from a specified path.
WorkBook workBook = WorkBook.Load(@"C:\Files\Customer Data.xlsx");
// Access the first worksheet from the workbook.
WorkSheet workSheet = workBook.WorkSheets.First();
// Convert the worksheet data to a DataTable object.
// The 'true' parameter uses the first row as column headers
var dataTable = workSheet.ToDataTable(true);
// Send the DataTable to the view for rendering.
return View(dataTable);
}
using IronXL;
using System.Data;
public ActionResult Index()
{
// Load the Excel workbook from a specified path.
WorkBook workBook = WorkBook.Load(@"C:\Files\Customer Data.xlsx");
// Access the first worksheet from the workbook.
WorkSheet workSheet = workBook.WorkSheets.First();
// Convert the worksheet data to a DataTable object.
// The 'true' parameter uses the first row as column headers
var dataTable = workSheet.ToDataTable(true);
// Send the DataTable to the view for rendering.
return View(dataTable);
}
Imports IronXL
Imports System.Data
Public Function Index() As ActionResult
' Load the Excel workbook from a specified path.
Dim workBook As WorkBook = WorkBook.Load("C:\Files\Customer Data.xlsx")
' Access the first worksheet from the workbook.
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
' Convert the worksheet data to a DataTable object.
' The 'true' parameter uses the first row as column headers
Dim dataTable = workSheet.ToDataTable(True)
' Send the DataTable to the view for rendering.
Return View(dataTable)
End Function
為何使用 DataTable 而非其他格式?
在 Index 動作方法中,請使用 IronXL 的 Load 方法載入 Excel 檔案。 Excel 檔案的路徑(包含檔案名稱)將作為參數傳遞給方法呼叫。 接著,請選取第一個 Excel 工作表作為工作表,並將其中所含的資料載入至 DataTable 物件中。 最後,將 DataTable 傳送至前端。
DataTable 非常適合用於 ASP.NET MVC,因為它能與 Razor 檢視無縫整合,並內建對行與列迭代的支援。 與自訂物件不同,DataTable 無需進行模型映射,並能自動處理混合資料類型。 您亦可於需要時將 DataSet 和 DataTable 匯出回 Excel。
關於檔案遺失的錯誤處理該如何處理?
完善的錯誤處理機制可確保,即使 Excel 檔案遺失或損毀,您的應用程式也不會當機。 以下是包含適當例外處理的增強版本:
public ActionResult Index()
{
try
{
string filePath = @"C:\Files\Customer Data.xlsx";
// Check if file exists before attempting to load
if (!System.IO.File.Exists(filePath))
{
ViewBag.Error = "Excel file not found at specified location.";
return View(new DataTable());
}
// Load workbook with error handling
WorkBook workBook = WorkBook.Load(filePath);
// Verify worksheet exists
if (workBook.WorkSheets.Count == 0)
{
ViewBag.Error = "No worksheets found in the Excel file.";
return View(new DataTable());
}
WorkSheet workSheet = workBook.WorkSheets.First();
var dataTable = workSheet.ToDataTable(true);
return View(dataTable);
}
catch (Exception ex)
{
// Log the exception (consider using a logging framework)
ViewBag.Error = $"Error reading Excel file: {ex.Message}";
return View(new DataTable());
}
}
public ActionResult Index()
{
try
{
string filePath = @"C:\Files\Customer Data.xlsx";
// Check if file exists before attempting to load
if (!System.IO.File.Exists(filePath))
{
ViewBag.Error = "Excel file not found at specified location.";
return View(new DataTable());
}
// Load workbook with error handling
WorkBook workBook = WorkBook.Load(filePath);
// Verify worksheet exists
if (workBook.WorkSheets.Count == 0)
{
ViewBag.Error = "No worksheets found in the Excel file.";
return View(new DataTable());
}
WorkSheet workSheet = workBook.WorkSheets.First();
var dataTable = workSheet.ToDataTable(true);
return View(dataTable);
}
catch (Exception ex)
{
// Log the exception (consider using a logging framework)
ViewBag.Error = $"Error reading Excel file: {ex.Message}";
return View(new DataTable());
}
}
Imports System.IO
Imports System.Data
Public Function Index() As ActionResult
Try
Dim filePath As String = "C:\Files\Customer Data.xlsx"
' Check if file exists before attempting to load
If Not File.Exists(filePath) Then
ViewBag.Error = "Excel file not found at specified location."
Return View(New DataTable())
End If
' Load workbook with error handling
Dim workBook As WorkBook = WorkBook.Load(filePath)
' Verify worksheet exists
If workBook.WorkSheets.Count = 0 Then
ViewBag.Error = "No worksheets found in the Excel file."
Return View(New DataTable())
End If
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim dataTable = workSheet.ToDataTable(True)
Return View(dataTable)
Catch ex As Exception
' Log the exception (consider using a logging framework)
ViewBag.Error = $"Error reading Excel file: {ex.Message}"
Return View(New DataTable())
End Try
End Function
如何選取不同的工作表?
IronXL 提供多種方式來選取及處理特定工作表。 您可以透過索引、名稱存取工作表,或遍歷所有可用工作表:
// Method 1: Select by worksheet name
WorkSheet namedSheet = workBook.GetWorkSheet("Sales Data");
// Method 2: Select by index (zero-based)
WorkSheet secondSheet = workBook.WorkSheets[1];
// Method 3: Select the default/active worksheet
WorkSheet defaultSheet = workBook.DefaultWorkSheet;
// Method 4: Iterate through all worksheets
foreach (WorkSheet sheet in workBook.WorkSheets)
{
string sheetName = sheet.Name;
// Process each worksheet
}
// Method 1: Select by worksheet name
WorkSheet namedSheet = workBook.GetWorkSheet("Sales Data");
// Method 2: Select by index (zero-based)
WorkSheet secondSheet = workBook.WorkSheets[1];
// Method 3: Select the default/active worksheet
WorkSheet defaultSheet = workBook.DefaultWorkSheet;
// Method 4: Iterate through all worksheets
foreach (WorkSheet sheet in workBook.WorkSheets)
{
string sheetName = sheet.Name;
// Process each worksheet
}
' Method 1: Select by worksheet name
Dim namedSheet As WorkSheet = workBook.GetWorkSheet("Sales Data")
' Method 2: Select by index (zero-based)
Dim secondSheet As WorkSheet = workBook.WorkSheets(1)
' Method 3: Select the default/active worksheet
Dim defaultSheet As WorkSheet = workBook.DefaultWorkSheet
' Method 4: Iterate through all worksheets
For Each sheet As WorkSheet In workBook.WorkSheets
Dim sheetName As String = sheet.Name
' Process each worksheet
Next
如何在網頁上顯示 Excel 資料?
需要哪些 View Code?
下一個範例將展示如何在網頁瀏覽器中顯示前一個範例中返回的 DataTable。
此範例中使用的 Excel 工作檔如下所示:
Excel 檔案
開啟 index.cshtml(索引檢視),並將原始程式碼替換為以下 HTML 程式碼:
@{
ViewData["Title"] = "Home Page";
}
@using System.Data
@model DataTable
<div class="text-center">
<h1 class="display-4">Welcome to IronXL Read Excel MVC</h1>
</div>
@* Check for errors first *@
@if (ViewBag.Error != null)
{
<div class="alert alert-danger">
@ViewBag.Error
</div>
}
@* Display table only if data exists *@
@if (Model != null && Model.Rows.Count > 0)
{
<table class="table table-dark">
<tbody>
@foreach (DataRow row in Model.Rows)
{
<tr>
@for (int i = 0; i < Model.Columns.Count; i++)
{
<td>@row[i]</td>
}
</tr>
}
</tbody>
</table>
}
else
{
<p>No data to display.</p>
}
@{
ViewData["Title"] = "Home Page";
}
@using System.Data
@model DataTable
<div class="text-center">
<h1 class="display-4">Welcome to IronXL Read Excel MVC</h1>
</div>
@* Check for errors first *@
@if (ViewBag.Error != null)
{
<div class="alert alert-danger">
@ViewBag.Error
</div>
}
@* Display table only if data exists *@
@if (Model != null && Model.Rows.Count > 0)
{
<table class="table table-dark">
<tbody>
@foreach (DataRow row in Model.Rows)
{
<tr>
@for (int i = 0; i < Model.Columns.Count; i++)
{
<td>@row[i]</td>
}
</tr>
}
</tbody>
</table>
}
else
{
<p>No data to display.</p>
}
為何要使用 Bootstrap 進行表格樣式設計?
上述程式碼以 Index 方法所返回的 DataTable 作為範例。 表格中的每一行皆透過 @for 迴圈 PRINT 至網頁,並包含 Bootstrap 格式設定以進行美化。
Bootstrap 提供響應式表格設計,能自動適應不同螢幕尺寸——這對現代網路應用程式至關重要。 table-dark 類別可建立美觀且易於閱讀的深色主題表格。 若需進行更進階的 Excel 格式設定(例如儲存格邊框與對齊方式,或背景圖案與顏色),IronXL 提供了額外的方法,可直接存取結構化資料。
最終輸出應呈現何種樣貌?
執行此專案將產生如下結果:
Bootstrap 表格
如何在表格中添加標題?
若要顯示 Excel 檔案中的欄位標題,請修改檢視程式碼,加入表格標題區段。 呼叫 ToDataTable(true) 時,IronXL 會自動將第一行用作欄位名稱:
@if (Model != null && Model.Rows.Count > 0)
{
<table class="table table-dark">
<thead>
<tr>
@foreach (DataColumn column in Model.Columns)
{
<th>@column.ColumnName</th>
}
</tr>
</thead>
<tbody>
@foreach (DataRow row in Model.Rows)
{
<tr>
@for (int i = 0; i < Model.Columns.Count; i++)
{
<td>@row[i]</td>
}
</tr>
}
</tbody>
</table>
}
@if (Model != null && Model.Rows.Count > 0)
{
<table class="table table-dark">
<thead>
<tr>
@foreach (DataColumn column in Model.Columns)
{
<th>@column.ColumnName</th>
}
</tr>
</thead>
<tbody>
@foreach (DataRow row in Model.Rows)
{
<tr>
@for (int i = 0; i < Model.Columns.Count; i++)
{
<td>@row[i]</td>
}
</tr>
}
</tbody>
</table>
}
此增強功能會從您的 Excel 檔案中顯示正確的欄位標題,例如"客戶名稱"、"運費"和"單價"。若涉及命名範圍或命名表格等更複雜的情境,IronXL 提供了額外的方法,可直接存取結構化資料。
常見問題
如何在沒有 Microsoft Office 的情況下,於 ASP.NET MVC 中讀取 Excel 檔案?
IronXL 讓您能夠直接在 C# 中讀取 Excel 檔案,無需依賴 Microsoft Office。只需透過 NuGet 安裝 IronXL,然後使用 WorkBook.Load() 開啟您的 Excel 檔案,並僅需一行程式碼即可將其轉換為 DataTable:var dataTable = IronXl.WorkBook.Load('CustomerData.xlsx').DefaultWorkSheet.ToDataTable(true);
在 ASP.NET 中,將 Excel 資料轉換為 DataTable 的最快方法是什麼?
IronXL 提供 ToDataTable() 方法,可立即將 Excel 工作表轉換為 System.Data.DataTable 物件。使用 IronXL 載入工作簿後,存取任何工作表並呼叫 ToDataTable(true) 即可包含標題列。此轉換僅需一行程式碼,並能與 ASP.NET MVC 檢視無縫整合。
在網頁應用程式中處理 Excel 檔案時,我應該使用哪個 .NET 版本?
IronXL 支援 .NET Framework 4.6.2 以上版本及 .NET Core 3.1 以上版本。針對新的 ASP.NET MVC 專案,建議使用 .NET 6.0 或更高版本,因為它在使用 IronXL 處理大型 Excel 檔案時提供了更佳的記憶體管理,並對試算表操作提供了更完善的 async/await 支援。
哪種 Visual Studio 專案範本最適合用於 Excel 讀取功能?
建立專案時,請選擇「ASP.NET Core Web App (Model-View-Controller)」範本。此 MVC 架構與 IronXL 的 DataTables 轉換功能完美契合,讓您能在控制器中載入並處理 Excel 檔案,同時在檢視層面清晰地呈現資料。
如何在我的 ASP.NET 專案中安裝 Excel 讀取函式庫?
請透過 NuGet 套件管理員控制台執行 'Install-Package IronXl.Excel' 來安裝 IronXL。安裝完成後,請檢查專案依賴項以確認是否已正確加入,並在控制器中加入 'using IronXL;' —— IntelliSense 應能立即識別該命名空間。

