使用 IronXL 在 ASP.NET MVC 中使用 C# 讀取 Excel 文件

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronXL 可讓 ASP.NET MVC 開發人員直接在 C# 中讀取 Excel 檔案,而無需 Microsoft Office 的相依性,僅需幾行程式碼即可將 Excel 資料轉換為 System.Data.DataTable 以便在網頁檢視中輕鬆顯示。

快速入門:在 MVC 中載入 Excel 表格並將其轉換為 DataTable

本範例展示了如何在幾秒鐘內上手:載入 Excel 工作簿,選取其第一個工作表,並使用 IronXL 將其轉換為 System.Data.DataTable - 無需 Interop,沒有麻煩。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 IronXL

    PM > Install-Package IronXL.Excel

  2. 複製並運行這段程式碼。

    var dataTable = IronXL.WorkBook.Load("CustomerData.xlsx").DefaultWorkSheet.ToDataTable(true);
  3. 部署到您的生產環境進行測試

    立即開始在您的專案中使用 IronXL,免費試用!
    arrow pointer

如何建立 ASP.NET 專案供 Excel 閱讀?

為什麼 Visual Studio 2022 最適合用於此用途?

使用 Visual Studio 2022 建立一個新的 ASP.NET 專案。 Visual Studio 2022 提供了對 .NET 6+ Framework 的出色支援,改進了 IronXL 方法的 IntelliSense,並在處理大型 Excel 檔案時提供了更好的性能。 IDE 的 NuGet 整合使 IronXL 的安裝特別簡單直接。

我該選擇何種專案範本?

若要在 ASP.NET 中閱讀 Excel 檔案,請選擇"ASP.NET Core Web App (Model-View-Controller)"範本。 本範本提供簡潔的 MVC 架構,將資料處理 (Excel 讀取) 與簡報邏輯分離。 MVC 模式可與 IronXLDataTable 轉換完美搭配,讓您可以在控制器中載入試算表,並在檢視中無縫顯示。

建議使用哪個 .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 是否已正確安裝,請在 Solution Explorer 中檢查專案的相依性。 您應該可以在"相依性 > 套件"中看到"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
$vbLabelText   $csharpLabel

為何使用 DataTable 而非其他格式?

Index 動作方法中,使用 IronXLLoad 方法載入 Excel 檔案。 Excel 檔案的路徑(包括檔案名稱)會作為參數傳遞給方法呼叫。 接下來,選擇第一個 Excel 工作表作為工作表,並將其中包含的資料載入 DataTable 物件中。 最後,將 DataTable 傳送至前端。

DataTable 是 ASP.NET MVC 的理想選擇,因為它可與 Razor 視圖無縫整合,並提供內建的行列迭代支援。 與自訂物件不同,DataTable 不需要模型映射,並可自動處理混合資料類型。 您也可以在需要時將 DataSetDataTable 匯出回 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
$vbLabelText   $csharpLabel

如何選擇不同的工作表?

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
$vbLabelText   $csharpLabel

如何在網頁上顯示 Excel 資料?

需要哪些檢視程式碼?

下一個範例顯示如何在網頁瀏覽器中顯示上一個範例中傳回的 DataTable

本範例中使用的 Excel 檔案如下所示:

Excel spreadsheet with customer names, shipping costs, and unit prices - sample data for web display tutorial

Excel 檔案

開啟 index.cshtml (索引檢視),並以下列 HTML 程式碼取代該程式碼:

@{
    ViewData["Title"] = "Home Page";
}

@using System.Data
@model DataTable

<div class="text-center">
    <h1>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>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>
}
$vbLabelText   $csharpLabel

為什麼要使用 Bootstrap 來設計表格樣式?

上述程式碼使用Index方法傳回的DataTable作為模型。 使用@for迴圈將表格中的每一行列印到網頁上,並包含 Bootstrap 格式進行裝飾。

Bootstrap 提供可自動依據不同螢幕尺寸調整的回應式表格設計 - 這對於現代網路應用程式而言至關重要。 table-dark 類別可建立容易閱讀的迷人深色主題表格。 對於更進階的 Excel 格式化,例如儲存格邊界與對齊方式背景圖案與顏色IronXL提供了額外的方法來直接存取結構化資料。

最終輸出是什麼樣子?

執行專案的結果如下所示:

Bootstrap table displaying Excel customer data with names, shipping costs, and unit prices in ASP.NET MVC application

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>
}
$vbLabelText   $csharpLabel

此增強功能可從 Excel 檔案中顯示適當的欄頭,例如"客戶名稱"、"運費"和"單價"。對於涉及 named rangesnamed tables 的更複雜情況,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.Excel 提供 ToDataTable() 方法,可立即將 Excel 工作表轉換為 System.Data.DataTable 物件。使用 IronXL 載入工作簿後,存取任何工作表並呼叫 ToDataTable(true) 以包含表頭。此轉換只需一行程式碼,並可與 ASP.NET MVC 視圖無縫運作。

Web 應用程式中的 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.Excel 的 DataTable 轉換功能,讓您可以在控制器中載入和處理 Excel 檔案,同時在檢視中乾淨地顯示資料。

如何在我的 ASP.NET 專案中安裝 Excel 閱讀函式庫?

透過 NuGet 套件管理員控制台執行「Install-Package IronXL.Excel」安裝 IronXL。安裝完成後,請檢查專案的相依性,並在控制器中加入「using IronXL;」,以驗證是否已正確加入 - IntelliSense 應該會立即辨識命名空間。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。

準備好開始了嗎?
Nuget 下載 1,846,091 | 版本: 2026.2 剛剛發布