跳至頁尾內容
USING IRONXL

如何使用 C# 中的 Interop 而非 IronXL 將資料表匯出到 Excel

為什麼將DataTable導出到Excel對.NET開發者很重要?

從資料庫或應用程式導出資料到Excel文件是需要有效分析、視覺化和共享資訊的組織的一個基本需求。 Excel文件以其使用者友好的介面而廣為人知,使最終使用者可以輕鬆地與資料交互和解釋。 通過將資料集轉換為.xlsx格式,開發人員可以確保無論接收者的技術背景如何,資料仍然易於存取且結構良好。

對於.NET開發者,存在兩種常見的方法:微軟Office Interop和專用的Excel庫,如IronXL。 本指南以工作C#程式碼範例介紹了這兩種方法,解釋了它們的權衡,並說明在生產應用中每種方法何時有意義。

Interop 和 IronXL 之間的主要區別是什麼?

在深入程式碼之前,了解這兩種方法之間的基本區別有助於為任何項目選擇正確的方案。 比較涵蓋了技術架構、部署要求以及在 DataTable 到 Excel 導出場景中工作的實際開發體驗。

C# 中Microsoft Office Interop與IronXL的Excel導出比較
功能 Microsoft Office Interop IronXL
需要Office安裝 是 -- 必須安裝Microsoft Excel 否 -- 獨立的庫
伺服器端支持 微軟不推薦 完全支持
平台支持 僅限Windows Windows、Linux、macOS、Azure
.NET Core / .NET 5+ 支持 有限 完全支持(.NET 6、7、8、9、10)
資源管理 需要清理COM對像 標準.NET處理
安裝方法 COM參考 + Office安裝 NuGet package
執行緒模型 單執行緒公寓(STA) 執行緒安全操作
大資料集 記憶體密集型處理 高效的基於文件的方法
支持的文件格式 XLSX, XLS, CSV XLSX, XLS, CSV, JSON, XML
授權 需要Office授權 可用的商業授權

結構上的差異是基本的:Excel Interop通過COM自動化Microsoft Excel應用,而IronXL直接讀寫Excel文件格式,而無需啟動任何外部進程。 此區別會影響從記憶體使用到部署複雜性的各個方面。

如何安裝IronXL以匯出Excel?

通過NuGet安裝IronXL只需幾秒鐘。 不需要額外的軟體、Office安裝或系統配置。 無論是在Windows、Linux還是macOS上,包括Azure App Services、Azure Functions、容器實例,該庫在安裝後立即運行。

打開NuGet Package Manager Console並運行:

Install-Package IronXL.Excel

IronXL支持.NET Framework 4.6.2+和所有現代.NET版本(通過.NET 10)。安裝後,將using IronXL;新增到您的文件頂部,您就可以開始導出。

如何使用Interop將DataTable導出到Excel中?

傳統的方法使用Microsoft.Office.Interop.Excel命名空間來直接自動化Excel。 此方法需要在運行程式碼的機器上安裝Microsoft Excel。

Interop的先決條件

在使用Interop之前,請確認:

  1. Microsoft Excel已安裝在開發和部署機器上。
  2. 在Visual Studio中新增了"Microsoft Excel Object Library"的COM參考。
  3. 在您的專案中包含Microsoft.Office.Interop.Excel命名空間。

Interop導出程式碼

以下程式碼演示了如何使用Microsoft Office Interop在C#中使用頂級語句將DataTable導出到Excel文件:

using Microsoft.Office.Interop.Excel;
using System.Data;
using System.Runtime.InteropServices;

// Create a sample DataTable with employee data
DataTable dt = new DataTable("Employees");
dt.Columns.Add("EmployeeID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Department", typeof(string));
dt.Columns.Add("Salary", typeof(decimal));

dt.Rows.Add(1, "John Smith", "Engineering", 75000);
dt.Rows.Add(2, "Sarah Johnson", "Marketing", 65000);
dt.Rows.Add(3, "Michael Chen", "Finance", 70000);
dt.Rows.Add(4, "Emily Davis", "Engineering", 80000);

// Initialize Excel Application object
Application excelApp = new Application
{
    Visible = false,
    DisplayAlerts = false
};

Workbook workbook = excelApp.Workbooks.Add();
Worksheet worksheet = (Worksheet)workbook.ActiveSheet;

try
{
    // Write column headers to the first row
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
    }

    // Write data rows starting from row 2
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            worksheet.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
        }
    }

    string filePath = @"C:\Reports\EmployeeReport_Interop.xlsx";
    workbook.SaveAs(filePath);
    Console.WriteLine("Excel file created using Interop.");
}
catch (Exception ex)
{
    Console.WriteLine("Error: " + ex.Message);
}
finally
{
    // Always release COM objects to prevent orphaned Excel processes
    workbook.Close();
    excelApp.Quit();
    Marshal.ReleaseComObject(worksheet);
    Marshal.ReleaseComObject(workbook);
    Marshal.ReleaseComObject(excelApp);
}
using Microsoft.Office.Interop.Excel;
using System.Data;
using System.Runtime.InteropServices;

// Create a sample DataTable with employee data
DataTable dt = new DataTable("Employees");
dt.Columns.Add("EmployeeID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Department", typeof(string));
dt.Columns.Add("Salary", typeof(decimal));

dt.Rows.Add(1, "John Smith", "Engineering", 75000);
dt.Rows.Add(2, "Sarah Johnson", "Marketing", 65000);
dt.Rows.Add(3, "Michael Chen", "Finance", 70000);
dt.Rows.Add(4, "Emily Davis", "Engineering", 80000);

// Initialize Excel Application object
Application excelApp = new Application
{
    Visible = false,
    DisplayAlerts = false
};

Workbook workbook = excelApp.Workbooks.Add();
Worksheet worksheet = (Worksheet)workbook.ActiveSheet;

try
{
    // Write column headers to the first row
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
    }

    // Write data rows starting from row 2
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            worksheet.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
        }
    }

    string filePath = @"C:\Reports\EmployeeReport_Interop.xlsx";
    workbook.SaveAs(filePath);
    Console.WriteLine("Excel file created using Interop.");
}
catch (Exception ex)
{
    Console.WriteLine("Error: " + ex.Message);
}
finally
{
    // Always release COM objects to prevent orphaned Excel processes
    workbook.Close();
    excelApp.Quit();
    Marshal.ReleaseComObject(worksheet);
    Marshal.ReleaseComObject(workbook);
    Marshal.ReleaseComObject(excelApp);
}
Imports Microsoft.Office.Interop.Excel
Imports System.Data
Imports System.Runtime.InteropServices

' Create a sample DataTable with employee data
Dim dt As New DataTable("Employees")
dt.Columns.Add("EmployeeID", GetType(Integer))
dt.Columns.Add("Name", GetType(String))
dt.Columns.Add("Department", GetType(String))
dt.Columns.Add("Salary", GetType(Decimal))

dt.Rows.Add(1, "John Smith", "Engineering", 75000)
dt.Rows.Add(2, "Sarah Johnson", "Marketing", 65000)
dt.Rows.Add(3, "Michael Chen", "Finance", 70000)
dt.Rows.Add(4, "Emily Davis", "Engineering", 80000)

' Initialize Excel Application object
Dim excelApp As New Application With {
    .Visible = False,
    .DisplayAlerts = False
}

Dim workbook As Workbook = excelApp.Workbooks.Add()
Dim worksheet As Worksheet = CType(workbook.ActiveSheet, Worksheet)

Try
    ' Write column headers to the first row
    For i As Integer = 0 To dt.Columns.Count - 1
        worksheet.Cells(1, i + 1) = dt.Columns(i).ColumnName
    Next

    ' Write data rows starting from row 2
    For i As Integer = 0 To dt.Rows.Count - 1
        For j As Integer = 0 To dt.Columns.Count - 1
            worksheet.Cells(i + 2, j + 1) = dt.Rows(i)(j).ToString()
        Next
    Next

    Dim filePath As String = "C:\Reports\EmployeeReport_Interop.xlsx"
    workbook.SaveAs(filePath)
    Console.WriteLine("Excel file created using Interop.")
Catch ex As Exception
    Console.WriteLine("Error: " & ex.Message)
Finally
    ' Always release COM objects to prevent orphaned Excel processes
    workbook.Close()
    excelApp.Quit()
    Marshal.ReleaseComObject(worksheet)
    Marshal.ReleaseComObject(workbook)
    Marshal.ReleaseComObject(excelApp)
End Try
$vbLabelText   $csharpLabel

Application物件代表Excel進程本身。 設置Visible = false可以防止在處理期間Excel出現在螢幕上,這對於後台操作至關重要。 DisplayAlerts = false設置抑制那些會中斷自動化工作流程的對話框。

必須顯式使用Marshal.ReleaseComObject釋放每個COM物件。 省略此步驟會導致在任務管理器中留下孤立的Excel進程,消耗記憶體並最終破壞伺服器。 此清理模式是一個眾所周知的痛點,使Interop不適合用於Web應用程式和服務。

如何使用IronXL將DataTable導出到Excel?

IronXL提供了一個現代化的替代方案,無需任何Office安裝。 該庫直接讀取和寫入Excel文件,非常適合伺服器環境、雲端部署和跨平台應用程式。 查看完整的IronXL文件以查看更多API詳情。

IronXL導出程式碼

以下程式碼顯示瞭如何使用IronXL庫將DataTable轉換為Excel文件,並使用頂級語句:

using IronXL;
using System.Data;

// Create a sample DataTable
DataTable dt = new DataTable("Employees");
dt.Columns.Add("EmployeeID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Department", typeof(string));
dt.Columns.Add("Salary", typeof(decimal));

dt.Rows.Add(1, "John Smith", "Engineering", 75000);
dt.Rows.Add(2, "Sarah Johnson", "Marketing", 65000);
dt.Rows.Add(3, "Michael Chen", "Finance", 70000);
dt.Rows.Add(4, "Emily Davis", "Engineering", 80000);

// Create a new Excel workbook
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workbook.CreateWorkSheet("Employees");

// Write column headers to row 0
for (int i = 0; i < dt.Columns.Count; i++)
{
    sheet.SetCellValue(0, i, dt.Columns[i].ColumnName);
}

// Export DataTable rows to Excel cells
for (int i = 0; i < dt.Rows.Count; i++)
{
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        sheet.SetCellValue(i + 1, j, dt.Rows[i][j]);
    }
}

string filePath = @"C:\Reports\EmployeeReport_IronXL.xlsx";
workbook.SaveAs(filePath);
Console.WriteLine("Excel file created using IronXL.");
using IronXL;
using System.Data;

// Create a sample DataTable
DataTable dt = new DataTable("Employees");
dt.Columns.Add("EmployeeID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Department", typeof(string));
dt.Columns.Add("Salary", typeof(decimal));

dt.Rows.Add(1, "John Smith", "Engineering", 75000);
dt.Rows.Add(2, "Sarah Johnson", "Marketing", 65000);
dt.Rows.Add(3, "Michael Chen", "Finance", 70000);
dt.Rows.Add(4, "Emily Davis", "Engineering", 80000);

// Create a new Excel workbook
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workbook.CreateWorkSheet("Employees");

// Write column headers to row 0
for (int i = 0; i < dt.Columns.Count; i++)
{
    sheet.SetCellValue(0, i, dt.Columns[i].ColumnName);
}

// Export DataTable rows to Excel cells
for (int i = 0; i < dt.Rows.Count; i++)
{
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        sheet.SetCellValue(i + 1, j, dt.Rows[i][j]);
    }
}

string filePath = @"C:\Reports\EmployeeReport_IronXL.xlsx";
workbook.SaveAs(filePath);
Console.WriteLine("Excel file created using IronXL.");
Imports IronXL
Imports System.Data

' Create a sample DataTable
Dim dt As New DataTable("Employees")
dt.Columns.Add("EmployeeID", GetType(Integer))
dt.Columns.Add("Name", GetType(String))
dt.Columns.Add("Department", GetType(String))
dt.Columns.Add("Salary", GetType(Decimal))

dt.Rows.Add(1, "John Smith", "Engineering", 75000)
dt.Rows.Add(2, "Sarah Johnson", "Marketing", 65000)
dt.Rows.Add(3, "Michael Chen", "Finance", 70000)
dt.Rows.Add(4, "Emily Davis", "Engineering", 80000)

' Create a new Excel workbook
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim sheet As WorkSheet = workbook.CreateWorkSheet("Employees")

' Write column headers to row 0
For i As Integer = 0 To dt.Columns.Count - 1
    sheet.SetCellValue(0, i, dt.Columns(i).ColumnName)
Next

' Export DataTable rows to Excel cells
For i As Integer = 0 To dt.Rows.Count - 1
    For j As Integer = 0 To dt.Columns.Count - 1
        sheet.SetCellValue(i + 1, j, dt.Rows(i)(j))
    Next
Next

Dim filePath As String = "C:\Reports\EmployeeReport_IronXL.xlsx"
workbook.SaveAs(filePath)
Console.WriteLine("Excel file created using IronXL.")
$vbLabelText   $csharpLabel

IronXL方法遵循類似的邏輯結構,但具備更清晰的語法,且沒有COM的複雜性。 使用指定格式初始化新工作簿的方法——ExcelFileFormat.XLSX產生與Excel 2007及更高版本相容的現代Office Open XML文件。 該庫還支持流傳統系統的XLS。

SetCellValue使用符合標準.NET慣例的0基索引,減少了在不同索引系統之間轉換時常見的越界錯誤。 該方法自動處理型別轉換:整數、字串、小數以及DateTime值以適當的Excel單元格型別寫入。

注意清理程式碼的完整缺失。 IronXL物件是標準的.NET托管物件,垃圾回收器會自動處理。 沒有孤立進程或COM引用計數需要管理的風險。

How to Export DataTable to Excel C# Using Interop vs IronXL: Image 1 - Excel Output

How to Export DataTable to Excel C# Using Interop vs IronXL: Image 2 - Console Output

有關工作簿建立的更多資訊,請參見IronXL建立試算表指南

您如何建立可重複使用的導出方法?

生產應用程式經常需要一個可重複使用的方法來將任何DataTable導出到Excel文件。以下範例展示了一個幫助程式,它將導出邏輯封裝處理掉了以及null值,並自動建立輸出目錄(如果不存在)。查看IronXL範例頁面以獲取更多模式。

可重複使用的IronXL導出助手

using IronXL;
using IronXL.Styles;
using System;
using System.Data;
using System.IO;

// --- ExcelExporter helper ---

bool ExportToExcel(DataTable dt, string filePath)
{
    if (dt == null || dt.Rows.Count == 0)
        return false;

    try
    {
        WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        WorkSheet sheet = workbook.CreateWorkSheet(dt.TableName ?? "Sheet1");

        // Bold headers in the first row
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            var cell = sheet.GetCellAt(0, i);
            cell.Value = dt.Columns[i].ColumnName;
            cell.Style.Font.Bold = true;
        }

        // Data rows
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                var value = dt.Rows[i][j];
                sheet.SetCellValue(
                    i + 1, j,
                    (value == DBNull.Value || value == null) ? "" : value
                );
            }
        }

        FileInfo fileInfo = new FileInfo(filePath);
        if (!fileInfo.Directory!.Exists)
            fileInfo.Directory.Create();

        workbook.SaveAs(filePath);
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Export failed: " + ex.Message);
        return false;
    }
}

// --- Usage ---

DataTable employees = new DataTable("Employees");
employees.Columns.Add("EmployeeID", typeof(int));
employees.Columns.Add("Name", typeof(string));
employees.Columns.Add("Department", typeof(string));
employees.Rows.Add(1, "John Smith", "Engineering");
employees.Rows.Add(2, "Sarah Johnson", "Marketing");

bool success = ExportToExcel(employees, @"C:\Reports\Export.xlsx");
Console.WriteLine(success ? "Export completed." : "Export failed.");
using IronXL;
using IronXL.Styles;
using System;
using System.Data;
using System.IO;

// --- ExcelExporter helper ---

bool ExportToExcel(DataTable dt, string filePath)
{
    if (dt == null || dt.Rows.Count == 0)
        return false;

    try
    {
        WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        WorkSheet sheet = workbook.CreateWorkSheet(dt.TableName ?? "Sheet1");

        // Bold headers in the first row
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            var cell = sheet.GetCellAt(0, i);
            cell.Value = dt.Columns[i].ColumnName;
            cell.Style.Font.Bold = true;
        }

        // Data rows
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                var value = dt.Rows[i][j];
                sheet.SetCellValue(
                    i + 1, j,
                    (value == DBNull.Value || value == null) ? "" : value
                );
            }
        }

        FileInfo fileInfo = new FileInfo(filePath);
        if (!fileInfo.Directory!.Exists)
            fileInfo.Directory.Create();

        workbook.SaveAs(filePath);
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Export failed: " + ex.Message);
        return false;
    }
}

// --- Usage ---

DataTable employees = new DataTable("Employees");
employees.Columns.Add("EmployeeID", typeof(int));
employees.Columns.Add("Name", typeof(string));
employees.Columns.Add("Department", typeof(string));
employees.Rows.Add(1, "John Smith", "Engineering");
employees.Rows.Add(2, "Sarah Johnson", "Marketing");

bool success = ExportToExcel(employees, @"C:\Reports\Export.xlsx");
Console.WriteLine(success ? "Export completed." : "Export failed.");
Imports IronXL
Imports IronXL.Styles
Imports System
Imports System.Data
Imports System.IO

' --- ExcelExporter helper ---

Function ExportToExcel(dt As DataTable, filePath As String) As Boolean
    If dt Is Nothing OrElse dt.Rows.Count = 0 Then
        Return False
    End If

    Try
        Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
        Dim sheet As WorkSheet = workbook.CreateWorkSheet(If(dt.TableName, "Sheet1"))

        ' Bold headers in the first row
        For i As Integer = 0 To dt.Columns.Count - 1
            Dim cell = sheet.GetCellAt(0, i)
            cell.Value = dt.Columns(i).ColumnName
            cell.Style.Font.Bold = True
        Next

        ' Data rows
        For i As Integer = 0 To dt.Rows.Count - 1
            For j As Integer = 0 To dt.Columns.Count - 1
                Dim value = dt.Rows(i)(j)
                sheet.SetCellValue(i + 1, j, If(value Is DBNull.Value OrElse value Is Nothing, "", value))
            Next
        Next

        Dim fileInfo As New FileInfo(filePath)
        If Not fileInfo.Directory.Exists Then
            fileInfo.Directory.Create()
        End If

        workbook.SaveAs(filePath)
        Return True
    Catch ex As Exception
        Console.WriteLine("Export failed: " & ex.Message)
        Return False
    End Try
End Function

' --- Usage ---

Dim employees As New DataTable("Employees")
employees.Columns.Add("EmployeeID", GetType(Integer))
employees.Columns.Add("Name", GetType(String))
employees.Columns.Add("Department", GetType(String))
employees.Rows.Add(1, "John Smith", "Engineering")
employees.Rows.Add(2, "Sarah Johnson", "Marketing")

Dim success As Boolean = ExportToExcel(employees, "C:\Reports\Export.xlsx")
Console.WriteLine(If(success, "Export completed.", "Export failed."))
$vbLabelText   $csharpLabel

false。 它通過在寫入單元格之前檢查DBNull.Value來優雅地處理缺失值。 建立目錄步驟防止DirectoryNotFoundException打斷計劃在新文件夾路徑中進行的導出——新環境部署時常見的生產問題。

使用cell.Style.Font.Bold = true加粗標題,產生專業外觀的輸出,無需額外配置。 此模式易於擴展:新增背景色、邊框或列寬自適應以符合您組織的報告標準。

處理大資料集時,IronXL性能指南涵蓋了最大限度減少記憶體分配的大批量寫入策略。 該庫還支持導出DataTable物件集合——到單個工作簿中的多個工作表,用於多工作表報表非常有用。

兩種方法如何處理單元格式化?

專業的Excel導出經常需要格式化:加粗標題、着色單元格、邊框和數字格式。 兩個庫都支持樣式設計,但在冗長性和可靠性方面的實現差異顯著。

使用IronXL格式化

using IronXL;
using IronXL.Styles;
using System.Data;

DataTable dt = new DataTable("Sales");
dt.Columns.Add("Product", typeof(string));
dt.Columns.Add("Revenue", typeof(decimal));
dt.Rows.Add("Widget A", 15000.50m);
dt.Rows.Add("Widget B", 22500.75m);

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workbook.CreateWorkSheet("Sales");

// Write headers with light blue background and bold font
for (int i = 0; i < dt.Columns.Count; i++)
{
    var cell = sheet.GetCellAt(0, i);
    cell.Value = dt.Columns[i].ColumnName;
    cell.Style.Font.Bold = true;
    cell.Style.SetBackgroundColor("#ADD8E6");
    cell.Style.BottomBorder.SetColor("#000000");
    cell.Style.BottomBorder.Type = BorderType.Thin;
}

// Write data rows
for (int i = 0; i < dt.Rows.Count; i++)
{
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        sheet.SetCellValue(i + 1, j, dt.Rows[i][j]);
    }
}

workbook.SaveAs(@"C:\Reports\FormattedReport_IronXL.xlsx");
Console.WriteLine("Formatted Excel file created.");
using IronXL;
using IronXL.Styles;
using System.Data;

DataTable dt = new DataTable("Sales");
dt.Columns.Add("Product", typeof(string));
dt.Columns.Add("Revenue", typeof(decimal));
dt.Rows.Add("Widget A", 15000.50m);
dt.Rows.Add("Widget B", 22500.75m);

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workbook.CreateWorkSheet("Sales");

// Write headers with light blue background and bold font
for (int i = 0; i < dt.Columns.Count; i++)
{
    var cell = sheet.GetCellAt(0, i);
    cell.Value = dt.Columns[i].ColumnName;
    cell.Style.Font.Bold = true;
    cell.Style.SetBackgroundColor("#ADD8E6");
    cell.Style.BottomBorder.SetColor("#000000");
    cell.Style.BottomBorder.Type = BorderType.Thin;
}

// Write data rows
for (int i = 0; i < dt.Rows.Count; i++)
{
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        sheet.SetCellValue(i + 1, j, dt.Rows[i][j]);
    }
}

workbook.SaveAs(@"C:\Reports\FormattedReport_IronXL.xlsx");
Console.WriteLine("Formatted Excel file created.");
Imports IronXL
Imports IronXL.Styles
Imports System.Data

Dim dt As New DataTable("Sales")
dt.Columns.Add("Product", GetType(String))
dt.Columns.Add("Revenue", GetType(Decimal))
dt.Rows.Add("Widget A", 15000.50D)
dt.Rows.Add("Widget B", 22500.75D)

Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim sheet As WorkSheet = workbook.CreateWorkSheet("Sales")

' Write headers with light blue background and bold font
For i As Integer = 0 To dt.Columns.Count - 1
    Dim cell = sheet.GetCellAt(0, i)
    cell.Value = dt.Columns(i).ColumnName
    cell.Style.Font.Bold = True
    cell.Style.SetBackgroundColor("#ADD8E6")
    cell.Style.BottomBorder.SetColor("#000000")
    cell.Style.BottomBorder.Type = BorderType.Thin
Next

' Write data rows
For i As Integer = 0 To dt.Rows.Count - 1
    For j As Integer = 0 To dt.Columns.Count - 1
        sheet.SetCellValue(i + 1, j, dt.Rows(i)(j))
    Next
Next

workbook.SaveAs("C:\Reports\FormattedReport_IronXL.xlsx")
Console.WriteLine("Formatted Excel file created.")
$vbLabelText   $csharpLabel

IronXL的樣式API使用乾淨的物件模型。 顏色值接受標準的十六進制程式碼,例如#ADD8E6(淺藍色),使匹配企業品牌logo成爲可能,無需在色彩系統之間進行轉換。 BorderType.Thick涵蓋了標準的邊框場景,無需查找枚舉。

How to Export DataTable to Excel C# Using Interop vs IronXL: Image 3 - Formatting with IronXL Output

有關所有樣式設計選項,包括數字格式、條件格式和單元合併,請參見IronXL單元樣式指南邊框與對齊文件

Interop 格式化複雜性

Interop等同於存取單個Borders.LineStyle等屬性。 每個屬性存取都是一個COM跨進程調用,增加了開銷,並且如果Excel變得無響應,則會提高出現異常的幾率。顏色值需要Marshal.ReleaseComObject调用。

當在大工作表上應用條件格式、列寬或數字格式時,這種冗長變得問題嚴重。 IronXL使用較少行程式碼處理相同場景,且無需擔憂崩潰後Excel進程仍在運行的風險。

.NET中Excel導出最佳實踐是什麼?

遵循一致的導出規程能減少錯誤,提高可維護性,並使您的程式碼更加易於測試和部署。

命名和路徑慣例

對导出文件使用一致的命名惯例:{ReportName}_{Timestamp}.xlsx。 可預測的文件名使自動清理和存檔變得簡單。 將輸出目錄儲存在應用程式配置中,而不是硬編碼路徑 - 這可防止DirectoryNotFoundException在新環境中部署時出現問題。

錯誤處理

將所有導出邏輯包在try-catch塊中,並記錄足夠上下文以診斷故障的例外情況。 對於計劃的導出,考慮返回結果物件而不是拋出異常,這樣調用服務可以在不會崩潰的情況下重試或提醒操作員。 上面的bool返回值。

大資料集處理

對於超過5萬行的資料集,以批次進行資料流,以避免記憶體壓力。 IronXL 支持漸進寫入,而OpenXML SDK為非常大的文件提供了低級流處理。 完全避免Interop進行大型資料集——其記憶體中模型在規模上會造成顯著的減速。

跨平台部署

如果應用程式在Linux或macOS上運行——例如在Docker容器或Azure Linux App Services中——IronXL是唯一可行的選擇。Interop在Windows之外運作無效,因為它依賴於Excel COM伺服器。 使用.NET跨平台部署指南確認所有依賴項在目標運行時是可用的。

測試

導出邏輯的單元測試應驗證輸出文件是否存在,是否包含預期行數,並使用正確的列名。 IronXL的WorkBook.Load方法使在無需啟動Excel的情況下讀回導出文件進行測試變得簡單。 參見IronXL閱讀指南以獲取範例。

您應該在什麼時候選擇每種方法?

正確的選擇取決於專案的具體需求、部署環境和長期維護考量。

在以下情況下選擇Microsoft Office Excel Interop:

  • 與已經依賴Interop的遺留系統合作,不可遷移。
  • 需要宏、資料透視表或圖表自動化等高級Excel功能,這需要完整的Excel應用物件模型。
  • 建立桌面應用程式,使用者已安裝Microsoft Excel,並且應用程式會互動運行。
  • 部署環境完全受控,僅限Windows,並且Office已經授權。
  • 自動化包含複雜嵌入公式或VBA程式碼的現有Excel模板。

在以下情況下選擇IronXL:

  • 建立Web應用程式、REST API或生成Excel文件導出的背景服務。
  • 部署到雲端環境如Azure App Services、AWS Lambda或Docker容器。
  • 需要Windows、Linux或MacOS部署的跨平台支持。
  • 使用.NET Framework 4.6.2+或現代.NET版本,並且Interop支持有限。
  • 需要可靠的資源管理,無COM清理問題。
  • 避免生產伺服器上的Office授權依賴。
  • 構建需要隔離Excel文件生成的多租戶應用。
  • 無需COM跨進程通信開銷即可高效處理大型資料集。
  • 需要導出到多種格式,包括XLSX、XLS、CSV、JSON和XML。

探索IronXL教程了解額外的情況,包括閱讀現有的Excel文件、處理公式以及管理多個工作表

您接下來的步驟是什麼?

DataTable導出到Excel文件是處理商業資料的.NET應用程式的一個基本需求。 無論來源是資料庫查詢、一個與多個相關表的DataSet,還是動態構建的記憶體集合,正確的庫選擇決定了部署的靈活性和長期的可維護性。

Microsoft Office Excel Interop多年來一直為開發者服務,但其依賴於Office安裝、COM的複雜性、不支持的伺服器場景和資源管理挑戰使其對於現代應用開發越來越不切實際。

IronXL提供了一個解決這些限制的更清晰的替代方案。 簡單的NuGet安裝,跨平台支持Windows、Linux和macOS,以及遵循.NET慣例的簡單API,消除了影響Excel Interop解決方案的部屬頭痛和資源管理陷阱。

開始,從NuGet安裝IronXL,複製上面的程式碼範例之一,並從測試DataTable快速導出。 IronXL快速入門指南在幾分鐘內涵蓋了大部分常見的場景。 當您準備好進入生產時,查看IronXL授權頁面以找到適合您團隊規模和部署模型的選項。 如需進一步探索,瀏覽完整的IronXL API參考IronXL GitHub儲存庫包括社區範例。

常見問題

使用IronXL代替Excel Interop匯出DataTables在C#中的主要優勢是什麼?

IronXL 提供一種更簡單、更有效的方法來將DataTables匯出到Excel C#中,而不需要在伺服器上安裝Excel。

IronXL可以處理大型DataTables在匯出到Excel時嗎?

是的,IronXL經過效能優化,可以處理大型DataTables,確保快速且可靠地匯出到Excel文件。

我需要安裝Microsoft Excel來使用IronXL匯出資料嗎?

不,IronXL不需要安裝Microsoft Excel,使其成為伺服器端應用程式的理想選擇。

IronXL如何簡化與Interop的DataTables匯出過程?

IronXL透過消除與Interop相關的繁瑣設置和依賴關係,提供了一個簡便的API用於DataTables匯出,從而簡化了過程。

IronXL是否與.NET core相容用於將DataTables匯出到Excel?

是的,IronXL完全相容於.NET Core,允許您在跨平台應用程式中將DataTables匯出到Excel。

IronXL可以將DataTables匯出到哪些文件格式?

IronXL可以將DataTables匯出到多種Excel文件格式,包括XLSX、XLS和CSV。

IronXL是否支援Excel工作表的樣式和格式化?

是的,IronXL支援進階的樣式和格式化選項,允許您從DataTables建立精美的Excel工作表。

我可以使用IronXL來自動化C#中的Excel相關任務嗎?

是的,IronXL可以用於自動化多種Excel相關的任務,從匯出DataTables到複雜的資料分析操作。

對於剛接觸IronXL的開發者,是否存在學習曲線?

IronXL被設計為直觀和易於學習,擁有豐富的文件和範例,幫助開發者快速入門。

使用IronXL在商業專案中有哪些授權選項?

IronXL提供多種授權選項,以滿足不同專案需求,包括用於商業用途的永久和訂閱授權。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話