如何在 C# 中建立一個 Excel 文件

How to Create an Excel File in C# (.NET Tutorial)

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

我所合作的大多數團隊至少和讀取它們一樣頻繁地需要生成Excel文件:發票、導出、財務團隊可以開啟和篩選的月報。 我已經在控制台應用、ASP.NET服務和後台工作中構建了這個流程無數次。 IronXL的API與Excel本身的思維接近,程式碼讀起來幾乎像規範,但有些格式和儲存決策比API表面上顯示的更為重要。 這份指南是我實際在生產中生成XLSX文件的方法,包括第一次遇到的陷阱。

該程式庫在.NET 8、.NET 9、.NET Core和.NET Framework上運行,在Windows、Linux、macOS、Azure和AWS上運行,無需主機上的Microsoft Office。以下的程式碼路徑在所有這些目標平台上一致。

快速開始:建立Excel文件

三行程式碼可以建立一個新的工作簿,在A1中寫入一個值,並保存文件到磁碟。 無需Excel進程,無需COM編組。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronXL.Excel

    PM > Install-Package IronXL.Excel
  2. 複製並運行這段程式碼片段。

    WorkBook book = IronXL.WorkBook.Create(IronXL.ExcelFileFormat.XLSX); book.CreateWorkSheet("Sheet1")["A1"].Value = "Hello World"; book.SaveAs("MyFile.xlsx");
  3. 部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronXL,透過免費試用

    arrow pointer

什麼是IronXL以及為什麼要用它來建立Excel文件?

IronXL是一個用於讀取、編輯和建立電子表格文件的C#和VB.NET Excel API。 它不需要Microsoft Office或Excel Interop,使部署簡化為一個NuGet引用和一個using指令。

IronXL完全支持.NET 9、.NET 8、.NET Core、.NET Framework、Xamarin、移動、Linux、macOS和Azure環境。

IronXL 特性

  • 直接由我們的.NET開發團隊提供人工支援
  • 與Microsoft Visual Studio的快速安裝
  • 免費開發使用。 授權從$999開始

我可以如何快速建立並保存Excel文件?

通過NuGet安裝IronXL直接下載DLLWorkBook類是所有Excel操作的入口點,而WorkSheet類則提供操作單個工作表的方法。 完整的逐步指導從下面的步驟1開始。


How Do I Install the IronXL C# Library?

在Visual Studio中的NuGet套件管理器中安裝IronXL,或者使用套件管理器控制台:

Install-Package IronXL.Excel

通過項目選單或在方案總管中右擊項目存取NuGet套件管理器。

Visual Studio項目選單顯示管理NuGet套件選項
圖3 - 通過項目選單存取NuGet套件管理器

方案總管理器上下文選單顯示管理NuGet套件選項
圖4 - 方案總管中的右鍵上下文選單

在軟體包列表中瀏覽IronXL.Excel並點擊安裝。


NuGet套件管理器顯示IronXL.Excel套件準備安裝
圖5 - 通過NuGet套件管理器安裝IronXL.Excel

或者,直接下載IronXL DLL並通過方案總管 > 參考 > 瀏覽IronXL.dll將其作為參考新增到您的專案中。

IronXL網站下載頁面顯示安裝說明和下載按鈕
圖6 - 從官網下載IronXL程式庫

請注意IronXL不需要Microsoft Office或Excel Interop安裝。 它可以在任何支持.NET的平台上運行,包括Windows、Linux、macOS和雲環境。)}


如何設置我的.NET專案?

IronXL可用於任何.NET專案型別:控制台應用、ASP.NET web應用、API或桌面工具。 下面的範例使用一個ASP.NET Web應用程式,但同樣的程式碼路徑適用於所有專案模板。

按照這些步驟建立一個ASP.NET網站:

  1. 打開Visual Studio
  2. 點擊文件 > 新建專案
  3. 在專案類別列表中選擇Visual C#下的Web
  4. 選擇ASP.NET Web 應用程式


    Visual Studio新建專案對話框選擇了ASP.NET Web應用程式

    圖1Create new ASP.NET project

  5. 點擊確定
  6. 選擇Web Forms模板

    ASP.NET項目模板選擇顯示Web Forms選項

    圖2Select Web Forms template

  7. 點擊確定

當您的專案準備好後,安裝IronXL以開始以程式化方式建立Excel文件。


How Do I Create an Excel Workbook in C#?

一個新的工作簿是對WorkBook.Create的單次調用,文件格式作為枚舉傳入:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-3.cs
WorkSheet workSheet = workBook.CreateWorkSheet("2020 Budget");
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("2020 Budget")
$vbLabelText   $csharpLabel

Create方法支持XLS(Excel 97-2003)和XLSX(Excel 2007+)兩種格式。 建議使用XLSX以獲得更好的性能和更小的文件大小。

  • XLSX:推薦用於所有現代Excel版本(2007+)—文件更小,性能更佳
  • XLS:用於相容Excel 97–2003的傳統格式

如何將工作表新增到我的工作簿?

通過CreateWorkSheet新增工作表:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-4.cs
workSheet["A1"].Value = "January";
workSheet["B1"].Value = "February";
workSheet["C1"].Value = "March";
workSheet["D1"].Value = "April";
workSheet["E1"].Value = "May";
workSheet["F1"].Value = "June";
workSheet["G1"].Value = "July";
workSheet["H1"].Value = "August";
workSheet["I1"].Value = "September";
workSheet["J1"].Value = "October";
workSheet["K1"].Value = "November";
workSheet["L1"].Value = "December";
workSheet("A1").Value = "January"
workSheet("B1").Value = "February"
workSheet("C1").Value = "March"
workSheet("D1").Value = "April"
workSheet("E1").Value = "May"
workSheet("F1").Value = "June"
workSheet("G1").Value = "July"
workSheet("H1").Value = "August"
workSheet("I1").Value = "September"
workSheet("J1").Value = "October"
workSheet("K1").Value = "November"
workSheet("L1").Value = "December"
$vbLabelText   $csharpLabel

一個工作簿包含一個或多個工作表。 每個工作表由行和列組成,行和列的交叉點是儲存格。 使用CreateWorkSheet方法將新表新增到您的工作簿中。

  • WorkBook.CreateWorkSheet(String):新增一個具有給定標籤名稱的新表
  • WorkSheet:通過名稱檢索現有的表單
  • 工作表名稱必須在一個工作簿內唯一

如何在Excel中設置儲存格值?

我怎樣才能手動設置儲存格值?

單元格存取使用您在Excel中看到的相同的A1樣式的地址字串:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-5.cs
Random r = new Random();
for (int i = 2 ; i <= 11 ; i++)
{
    workSheet["A" + i].Value = r.Next(1, 1000);
    workSheet["B" + i].Value = r.Next(1000, 2000);
    workSheet["C" + i].Value = r.Next(2000, 3000);
    workSheet["D" + i].Value = r.Next(3000, 4000);
    workSheet["E" + i].Value = r.Next(4000, 5000);
    workSheet["F" + i].Value = r.Next(5000, 6000);
    workSheet["G" + i].Value = r.Next(6000, 7000);
    workSheet["H" + i].Value = r.Next(7000, 8000);
    workSheet["I" + i].Value = r.Next(8000, 9000);
    workSheet["J" + i].Value = r.Next(9000, 10000);
    workSheet["K" + i].Value = r.Next(10000, 11000);
    workSheet["L" + i].Value = r.Next(11000, 12000);
}
Dim r As New Random()
For i As Integer = 2 To 11
	workSheet("A" & i).Value = r.Next(1, 1000)
	workSheet("B" & i).Value = r.Next(1000, 2000)
	workSheet("C" & i).Value = r.Next(2000, 3000)
	workSheet("D" & i).Value = r.Next(3000, 4000)
	workSheet("E" & i).Value = r.Next(4000, 5000)
	workSheet("F" & i).Value = r.Next(5000, 6000)
	workSheet("G" & i).Value = r.Next(6000, 7000)
	workSheet("H" & i).Value = r.Next(7000, 8000)
	workSheet("I" & i).Value = r.Next(8000, 9000)
	workSheet("J" & i).Value = r.Next(9000, 10000)
	workSheet("K" & i).Value = r.Next(10000, 11000)
	workSheet("L" & i).Value = r.Next(11000, 12000)
Next i
$vbLabelText   $csharpLabel

Value屬性接受字串、數字、日期和布林等多種資料型別。 IronXL自動根據資料型別設置儲存格格式。

如何動態設置儲存格值?

當行數在運行時已知時,字串插值使迴圈體易於讀取:

// Initialize random number generator for sample data
Random r = new Random();

// Populate cells with random budget data for each month
for (int i = 2; i <= 11; i++)
{
    // Set different budget categories with increasing ranges
    workSheet[$"A{i}"].Value = r.Next(1, 1000);     // Office Supplies
    workSheet[$"B{i}"].Value = r.Next(1000, 2000);  // Utilities
    workSheet[$"C{i}"].Value = r.Next(2000, 3000);  // Rent
    workSheet[$"D{i}"].Value = r.Next(3000, 4000);  // Salaries
    workSheet[$"E{i}"].Value = r.Next(4000, 5000);  // Marketing
    workSheet[$"F{i}"].Value = r.Next(5000, 6000);  // IT Services
    workSheet[$"G{i}"].Value = r.Next(6000, 7000);  // Travel
    workSheet[$"H{i}"].Value = r.Next(7000, 8000);  // Training
    workSheet[$"I{i}"].Value = r.Next(8000, 9000);  // Insurance
    workSheet[$"J{i}"].Value = r.Next(9000, 10000); // Equipment
    workSheet[$"K{i}"].Value = r.Next(10000, 11000); // Research
    workSheet[$"L{i}"].Value = r.Next(11000, 12000); // Misc
}

// Alternative: Set range of cells with same value
workSheet["A13:L13"].Value = 0; // Initialize totals row
// Initialize random number generator for sample data
Random r = new Random();

// Populate cells with random budget data for each month
for (int i = 2; i <= 11; i++)
{
    // Set different budget categories with increasing ranges
    workSheet[$"A{i}"].Value = r.Next(1, 1000);     // Office Supplies
    workSheet[$"B{i}"].Value = r.Next(1000, 2000);  // Utilities
    workSheet[$"C{i}"].Value = r.Next(2000, 3000);  // Rent
    workSheet[$"D{i}"].Value = r.Next(3000, 4000);  // Salaries
    workSheet[$"E{i}"].Value = r.Next(4000, 5000);  // Marketing
    workSheet[$"F{i}"].Value = r.Next(5000, 6000);  // IT Services
    workSheet[$"G{i}"].Value = r.Next(6000, 7000);  // Travel
    workSheet[$"H{i}"].Value = r.Next(7000, 8000);  // Training
    workSheet[$"I{i}"].Value = r.Next(8000, 9000);  // Insurance
    workSheet[$"J{i}"].Value = r.Next(9000, 10000); // Equipment
    workSheet[$"K{i}"].Value = r.Next(10000, 11000); // Research
    workSheet[$"L{i}"].Value = r.Next(11000, 12000); // Misc
}

// Alternative: Set range of cells with same value
workSheet["A13:L13"].Value = 0; // Initialize totals row
' Initialize random number generator for sample data
Dim r As New Random()

' Populate cells with random budget data for each month
For i As Integer = 2 To 11
	' Set different budget categories with increasing ranges
	workSheet($"A{i}").Value = r.Next(1, 1000) ' Office Supplies
	workSheet($"B{i}").Value = r.Next(1000, 2000) ' Utilities
	workSheet($"C{i}").Value = r.Next(2000, 3000) ' Rent
	workSheet($"D{i}").Value = r.Next(3000, 4000) ' Salaries
	workSheet($"E{i}").Value = r.Next(4000, 5000) ' Marketing
	workSheet($"F{i}").Value = r.Next(5000, 6000) ' IT Services
	workSheet($"G{i}").Value = r.Next(6000, 7000) ' Travel
	workSheet($"H{i}").Value = r.Next(7000, 8000) ' Training
	workSheet($"I{i}").Value = r.Next(8000, 9000) ' Insurance
	workSheet($"J{i}").Value = r.Next(9000, 10000) ' Equipment
	workSheet($"K{i}").Value = r.Next(10000, 11000) ' Research
	workSheet($"L{i}").Value = r.Next(11000, 12000) ' Misc
Next i

' Alternative: Set range of cells with same value
workSheet("A13:L13").Value = 0 ' Initialize totals row
$vbLabelText   $csharpLabel

字串插值($"...")使得簡單地引用動態單元格。 Item索引器支持單個儲存格和範圍。

如何從資料庫填充Excel?

從資料庫載入資料到Excel是一個常見的需求:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-7.cs
workSheet["A1:L1"].Style.SetBackgroundColor("#d3d3d3");
workSheet("A1:L1").Style.SetBackgroundColor("#d3d3d3")
$vbLabelText   $csharpLabel

此範例演示如何從資料庫讀取Excel資料,應用格式,並使用公式進行計算。 FormatString屬性啟用像Excel中一樣的自定義數字格式。


如何將格式應用於Excel儲存格?

我如何設置Excel中的背景顏色?

背景、交替行顏色和字體顏色覆蓋都通過Style物件應用於單元格或範圍:

// Set header row background to light gray using hex color
workSheet["A1:L1"].Style.SetBackgroundColor("#d3d3d3");

// Apply different colors for data categorization
workSheet["A2:A11"].Style.SetBackgroundColor("#E7F3FF"); // Light blue for January
workSheet["B2:B11"].Style.SetBackgroundColor("#FFF2CC"); // Light yellow for February

// Highlight important cells with bold colors
workSheet["L12"].Style.SetBackgroundColor("#FF0000"); // Red for totals
workSheet["L12"].Style.Font.SetColor("#FFFFFF"); // White text

// Create alternating row colors for better readability
for (int row = 2; row <= 11; row++)
{
    if (row % 2 == 0)
    {
        workSheet[$"A{row}:L{row}"].Style.SetBackgroundColor("#F2F2F2");
    }
}
// Set header row background to light gray using hex color
workSheet["A1:L1"].Style.SetBackgroundColor("#d3d3d3");

// Apply different colors for data categorization
workSheet["A2:A11"].Style.SetBackgroundColor("#E7F3FF"); // Light blue for January
workSheet["B2:B11"].Style.SetBackgroundColor("#FFF2CC"); // Light yellow for February

// Highlight important cells with bold colors
workSheet["L12"].Style.SetBackgroundColor("#FF0000"); // Red for totals
workSheet["L12"].Style.Font.SetColor("#FFFFFF"); // White text

// Create alternating row colors for better readability
for (int row = 2; row <= 11; row++)
{
    if (row % 2 == 0)
    {
        workSheet[$"A{row}:L{row}"].Style.SetBackgroundColor("#F2F2F2");
    }
}
' Set header row background to light gray using hex color
workSheet("A1:L1").Style.SetBackgroundColor("#d3d3d3")

' Apply different colors for data categorization
workSheet("A2:A11").Style.SetBackgroundColor("#E7F3FF") ' Light blue for January
workSheet("B2:B11").Style.SetBackgroundColor("#FFF2CC") ' Light yellow for February

' Highlight important cells with bold colors
workSheet("L12").Style.SetBackgroundColor("#FF0000") ' Red for totals
workSheet("L12").Style.Font.SetColor("#FFFFFF") ' White text

' Create alternating row colors for better readability
For row As Integer = 2 To 11
    If row Mod 2 = 0 Then
        workSheet($"A{row}:L{row}").Style.SetBackgroundColor("#F2F2F2")
    End If
Next row
$vbLabelText   $csharpLabel

SetBackgroundColor方法接受十六進制顏色程式碼。 配合Font.SetColor使用背景色,以確保在較暗的填充上對比可讀。

如何在Excel中建立邊框?

邊框可以幫助定義資料區域並改善結構:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-9.cs
// Use IronXL built-in aggregations
decimal sum = workSheet["A2:A11"].Sum();
decimal avg = workSheet["B2:B11"].Avg();
decimal max = workSheet["C2:C11"].Max();
decimal min = workSheet["D2:D11"].Min();

// Assign value to cells
workSheet["A12"].Value = sum;
workSheet["B12"].Value = avg;
workSheet["C12"].Value = max;
workSheet["D12"].Value = min;
' Use IronXL built-in aggregations
Dim sum As Decimal = workSheet("A2:A11").Sum()
Dim avg As Decimal = workSheet("B2:B11").Avg()
Dim max As Decimal = workSheet("C2:C11").Max()
Dim min As Decimal = workSheet("D2:D11").Min()

' Assign value to cells
workSheet("A12").Value = sum
workSheet("B12").Value = avg
workSheet("C12").Value = max
workSheet("D12").Value = min
$vbLabelText   $csharpLabel

IronXL支持多種邊框型別,包括細、中、厚、雙線、點線和虛線。 每個邊框邊都可以單獨設置樣式。


How Do I Use Excel Formulas in C#?

IronXL在寫入時評估Excel公式,因此值在工作簿保存後即為正確:

// Use built-in aggregation functions for ranges
decimal sum = workSheet["A2:A11"].Sum();
decimal avg = workSheet["B2:B11"].Avg();
decimal max = workSheet["C2:C11"].Max();
decimal min = workSheet["D2:D11"].Min();

// Assign calculated values to cells
workSheet["A12"].Value = sum;
workSheet["B12"].Value = avg;
workSheet["C12"].Value = max;
workSheet["D12"].Value = min;

// Or use Excel formulas directly
workSheet["A12"].Formula = "=SUM(A2:A11)";
workSheet["B12"].Formula = "=AVERAGE(B2:B11)";
workSheet["C12"].Formula = "=MAX(C2:C11)";
workSheet["D12"].Formula = "=MIN(D2:D11)";

// Complex formulas with multiple functions
workSheet["E12"].Formula = "=IF(SUM(E2:E11)>50000,\"Over Budget\",\"On Track\")";
workSheet["F12"].Formula = "=SUMIF(F2:F11,\">5000\")";

// Percentage calculations
workSheet["G12"].Formula = "=G11/SUM(G2:G11)*100";
workSheet["G12"].FormatString = "0.00%";

// Ensure all formulas calculate
workBook.EvaluateAll();
// Use built-in aggregation functions for ranges
decimal sum = workSheet["A2:A11"].Sum();
decimal avg = workSheet["B2:B11"].Avg();
decimal max = workSheet["C2:C11"].Max();
decimal min = workSheet["D2:D11"].Min();

// Assign calculated values to cells
workSheet["A12"].Value = sum;
workSheet["B12"].Value = avg;
workSheet["C12"].Value = max;
workSheet["D12"].Value = min;

// Or use Excel formulas directly
workSheet["A12"].Formula = "=SUM(A2:A11)";
workSheet["B12"].Formula = "=AVERAGE(B2:B11)";
workSheet["C12"].Formula = "=MAX(C2:C11)";
workSheet["D12"].Formula = "=MIN(D2:D11)";

// Complex formulas with multiple functions
workSheet["E12"].Formula = "=IF(SUM(E2:E11)>50000,\"Over Budget\",\"On Track\")";
workSheet["F12"].Formula = "=SUMIF(F2:F11,\">5000\")";

// Percentage calculations
workSheet["G12"].Formula = "=G11/SUM(G2:G11)*100";
workSheet["G12"].FormatString = "0.00%";

// Ensure all formulas calculate
workBook.EvaluateAll();
' Use built-in aggregation functions for ranges
Dim sum As Decimal = workSheet("A2:A11").Sum()
Dim avg As Decimal = workSheet("B2:B11").Avg()
Dim max As Decimal = workSheet("C2:C11").Max()
Dim min As Decimal = workSheet("D2:D11").Min()

' Assign calculated values to cells
workSheet("A12").Value = sum
workSheet("B12").Value = avg
workSheet("C12").Value = max
workSheet("D12").Value = min

' Or use Excel formulas directly
workSheet("A12").Formula = "=SUM(A2:A11)"
workSheet("B12").Formula = "=AVERAGE(B2:B11)"
workSheet("C12").Formula = "=MAX(C2:C11)"
workSheet("D12").Formula = "=MIN(D2:D11)"

' Complex formulas with multiple functions
workSheet("E12").Formula = "=IF(SUM(E2:E11)>50000,""Over Budget"",""On Track"")"
workSheet("F12").Formula = "=SUMIF(F2:F11,"">5000"")"

' Percentage calculations
workSheet("G12").Formula = "=G11/SUM(G2:G11)*100"
workSheet("G12").FormatString = "0.00%"

' Ensure all formulas calculate
workBook.EvaluateAll()
$vbLabelText   $csharpLabel

Range類提供如SumAverageMaxMin等方法以快速計算。 對於更複雜的情況,使用Formula屬性直接設定Excel公式。

提示當與範圍一起工作時,優先使用IronXL的內建.Sum().Avg().Max().Min()方法而不是原始公式字串。 它們是型別安全的,並且在編譯時避免公式語法錯誤。)}


如何設置工作表和列印屬性?

使用IronXL保護單個工作表,凍結行和列,以及設置列印格式選項。

如何設置工作表屬性?

保護工作表並控制顯示選項:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-11.cs
workSheet.SetPrintArea("A1:L12");
workSheet.PrintSetup.PrintOrientation = IronXL.Printing.PrintOrientation.Landscape;
workSheet.PrintSetup.PaperSize = IronXL.Printing.PaperSize.A4;
workSheet.SetPrintArea("A1:L12")
workSheet.PrintSetup.PrintOrientation = IronXL.Printing.PrintOrientation.Landscape
workSheet.PrintSetup.PaperSize = IronXL.Printing.PaperSize.A4
$vbLabelText   $csharpLabel

工作表保護防止意外修改,而凍結面板保持重要的行或列在滾動時可見。

凍結窗格
圖7 - 凍結頭行在滾動時保持可見

Excel保護對話框要求密碼以修改受保護工作表
圖8 - 密碼保護防止未授權的編輯

如何配置頁面和列印設置?

列印佈局選項(方向、紙張大小、頁邊距、縮放、頁眉、頁腳)均可通過WorkSheet.PrintSetup暴露:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-12.cs
workBook.SaveAs("Budget.xlsx");
workBook.SaveAs("Budget.xlsx")
$vbLabelText   $csharpLabel

IPrintSetup類提供全面的打配置選項,匹配Excel的列印設置。

Excel列印預覽顯示橫向方向和A4紙張大小設置
圖9 - 列印預覽中橫向方向與自定義頁邊距


如何保存我的Excel工作簿?

將您的工作簿另存為各種格式:

// Save as XLSX (recommended for modern Excel)
workBook.SaveAs("Budget.xlsx");

// Save as XLS for legacy compatibility
workBook.SaveAs("Budget.xls");

// Save as CSV for data exchange
workBook.SaveAsCsv("Budget.csv");

// Save as JSON for web applications
workBook.SaveAsJson("Budget.json");

// Save to stream for web downloads or cloud storage
using (var stream = new MemoryStream())
{
    workBook.SaveAs(stream);
    byte[] excelData = stream.ToArray();
    // Send to client or save to cloud
}

// Save with specific encoding for international characters
workBook.SaveAsCsv("Budget_UTF8.csv", System.Text.Encoding.UTF8);
// Save as XLSX (recommended for modern Excel)
workBook.SaveAs("Budget.xlsx");

// Save as XLS for legacy compatibility
workBook.SaveAs("Budget.xls");

// Save as CSV for data exchange
workBook.SaveAsCsv("Budget.csv");

// Save as JSON for web applications
workBook.SaveAsJson("Budget.json");

// Save to stream for web downloads or cloud storage
using (var stream = new MemoryStream())
{
    workBook.SaveAs(stream);
    byte[] excelData = stream.ToArray();
    // Send to client or save to cloud
}

// Save with specific encoding for international characters
workBook.SaveAsCsv("Budget_UTF8.csv", System.Text.Encoding.UTF8);
' Save as XLSX (recommended for modern Excel)
workBook.SaveAs("Budget.xlsx")

' Save as XLS for legacy compatibility
workBook.SaveAs("Budget.xls")

' Save as CSV for data exchange
workBook.SaveAsCsv("Budget.csv")

' Save as JSON for web applications
workBook.SaveAsJson("Budget.json")

' Save to stream for web downloads or cloud storage
Using stream = New MemoryStream()
	workBook.SaveAs(stream)
	Dim excelData() As Byte = stream.ToArray()
	' Send to client or save to cloud
End Using

' Save with specific encoding for international characters
workBook.SaveAsCsv("Budget_UTF8.csv", System.Text.Encoding.UTF8)
$vbLabelText   $csharpLabel

IronXL支援多種匯出格式,包括XLSX、XLS、CSV、TSV和JSON。 Save方法根據文件擴展名選擇格式。

  • XLSX / XLS:全Excel格式,含格式、公式和多個工作表
  • CSV:用於資料交換的純文字,每個文件一張工作表
  • JSON:用於web API和資料管道的結構化輸出
  • Stream:記憶體中的輸出,適用於web下載或雲儲存

生成實際需要多長時間?

對於大多數生產環境匯出最終會達到的工作簿大小——大約10,000行和少數幾欄——一旦程式預熱完成,生成並執行單次SaveAs寫入磁碟通常在一秒以內。 全新程式中的第一次執行較慢,因為它主要受IronXL的組件載入和JIT預熱所主導;後續執行會穩定在更快、相當穩定的範圍內,並因背景活動而有一些執行間的差異。 確切的時間取決於環境,因此請在您自己的目標硬體上進行測量,而不是依賴單一的公佈數字——下面CreateExcelBenchmark範例中可重現的測試工具能讓您正是這樣做。

對於顯著更大的工作簿(數十萬行、多張工作表、重度樣式),請將整個工作簿寫入記憶體,並在最後只呼叫一次SaveAs。 我們看到的「為什麼我的匯出這麼慢?」工單中,單一最常見的原因是在工作簿不斷增長時,於迴圈內反覆呼叫SaveAs:每次保存都會序列化整個當前狀態,因此成本會隨著每次迭代而攀升。


常見的陷阱

有幾件事經常讓人摔倒,以至於它們值得擁有自己的部份。

忘記在日期和貨幣上設定FormatString

我看到的最常見的格式陷阱:將.Value設為DateTime卻忘記FormatString。 日期儲存正確,但Excel將其顯示為原始序列號(45292表示2024-01-01)直到您應用格式字串如"yyyy-MM-dd"。 貨幣也有相同的問題:數字是正確的,但沒有"$#,##0.00"它顯示為裸小數。 我現在將值與格式寫在相鄰的行中,因此兩者不能彼此脫鈎:

var dateCell = sheet["A2"];
dateCell.Value = DateTime.Today;
dateCell.FormatString = "yyyy-MM-dd";

var moneyCell = sheet["B2"];
moneyCell.Value = 1499.95m;
moneyCell.FormatString = "$#,##0.00";
var dateCell = sheet["A2"];
dateCell.Value = DateTime.Today;
dateCell.FormatString = "yyyy-MM-dd";

var moneyCell = sheet["B2"];
moneyCell.Value = 1499.95m;
moneyCell.FormatString = "$#,##0.00";
Dim dateCell = sheet("A2")
dateCell.Value = DateTime.Today
dateCell.FormatString = "yyyy-MM-dd"

Dim moneyCell = sheet("B2")
moneyCell.Value = 1499.95D
moneyCell.FormatString = "$#,##0.00"
$vbLabelText   $csharpLabel

XLS將靜默截斷在65536行

本文頂部格選擇部分中提到此條目,但它在此列也贏得自己的位置,因為故障模式在靜默中: ExcelFileFormat.XLS在每個表的65,536行限制,並且在該限制之外的行將被刪除沒有例外或警告。 匯出"成功",而您的資料消失。 選擇XLSX作為任何資料密集型工作,除非下游系統根本無法讀取它。

"Excel說文件已損壞"

如果生成的文件拒絕打開或Excel表示它已損壞,原因幾乎總是兩件事之一。 要麼流沒有正確處理,因此磁碟上的位元組被截斷; 或者您寫入的位置仍被先前的運行鎖定,僅部分資料被吞噬。 請確保SaveAs(或包裝它的串流)在其他任何東西接觸該檔案之前已完全完成,並且最好在您用來包裝工作簿的任何MemoryStreamFileStream周圍使用using塊。

基準資料的範例專案

如果您想重現之前的時間資料,測試工具是一個小型.NET 9控制台應用:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-15.cs
// CreateExcelBenchmark/Program.cs (excerpt)
IronXL.License.LicenseKey = Environment.GetEnvironmentVariable("IRONXL_LICENSE_KEY");

var sw = Stopwatch.StartNew();
var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
var sheet = workbook.CreateWorkSheet("Data");
sheet["A1"].Value = "Id";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Amount";
for (int i = 0; i < 10_000; i++)
{
    int row = i + 2;
    sheet[$"A{row}"].Value = i + 1;
    sheet[$"B{row}"].Value = $"Item {i + 1}";
    sheet[$"C{row}"].Value = (i + 1) * 1.25m;
}
workbook.SaveAs("Generated.xlsx");
sw.Stop();
Console.WriteLine($"cold: {sw.Elapsed.TotalMilliseconds:F1} ms");
Imports System
Imports System.Diagnostics
Imports IronXL

Module Program
    Sub Main()
        License.LicenseKey = Environment.GetEnvironmentVariable("IRONXL_LICENSE_KEY")

        Dim sw As Stopwatch = Stopwatch.StartNew()
        Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
        Dim sheet As WorkSheet = workbook.CreateWorkSheet("Data")
        sheet("A1").Value = "Id"
        sheet("B1").Value = "Name"
        sheet("C1").Value = "Amount"
        For i As Integer = 0 To 9999
            Dim row As Integer = i + 2
            sheet($"A{row}").Value = i + 1
            sheet($"B{row}").Value = $"Item {i + 1}"
            sheet($"C{row}").Value = (i + 1) * 1.25D
        Next
        workbook.SaveAs("Generated.xlsx")
        sw.Stop()
        Console.WriteLine($"cold: {sw.Elapsed.TotalMilliseconds:F1} ms")
    End Sub
End Module
$vbLabelText   $csharpLabel

dotnet run -c Release下運行它,並插入您自己的行數、列數或樣式,以查看工作簿複雜性如何影響資料。


物件參考與資源

IronXL API參考覆蓋了本教程觸及的每個類和方法以及未觸及的。

附加教程用於相關Excel操作:

總結

IronXL.Excel生成XLSX、XLS、CSV和JSON格式的Excel工作簿,無需依賴於Microsoft Office或Interop。每個專案上的配方相同:建立工作簿,新增工作表,寫入值和公式,設置顯示所需的格式字串,並在最後保存一次。

準備好在生產中使用IronXL嗎? 開始您的免費試用查看授權選項

常見問題

如何在 C# 中不使用互操作建立 Excel 檔案?

您可以使用 IronXL 建立 Excel 檔案,它提供了一個簡單的 API:WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX)。這種方法可以在任何 .NET 平台上工作,無需安裝 Microsoft Office。

C# 支持哪些平台的 Excel 檔案建立?

IronXL 支持在 .NET 10、.NET 9、.NET 8、.NET Core、.NET Framework 4.6.2+ 上的 Excel 檔案建立,運行於 Windows、macOS、Linux、Docker、Azure 和 AWS 環境。

如何安裝 C# 的 Excel 生成程式庫?

通過 NuGet 套件管理器在 Visual Studio 中安裝 IronXL,使用命令 PM> Install-Package IronXL.Excel,或直接從 nuget.org 下載。

如何以程式方式建立新的 Excel 工作簿?

using IronXL 建立工作簿:WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX),然後使用 workbook.CreateWorkSheet("SheetName") 新增工作表。

如何使用 C# 在 Excel 工作表中設置單元格值?

using IronXL 的直觀語法設置單元格值:worksheet["A1"].Value = "Hello World" 或設置範圍:worksheet["A1:A10"].Value = 100

我可以以程式方式格式化 Excel 單元格嗎?

是的,IronXL 支持全面的格式化,包括背景顏色(cell.Style.SetBackgroundColor("#FF0000"))、邊框、字體和數字格式。

如何在 C# 中使用 Excel 公式?

using IronXL 的公式屬性應用公式:worksheet["A1"].Formula = "=SUM(B1:B10)",或使用內建方法如 range.Sum()range.Avg()

如何使用密碼保護 Excel 工作表?

using IronXL 保護工作表:worksheet.ProtectSheet("YourPassword") 以防止未經授權的修改。

如何配置 Excel 檔案的列印設置?

using IronXL 的 PrintSetup 設置列印屬性:worksheet.PrintSetup.PrintOrientation = PrintOrientation.Landscapeworksheet.SetPrintArea("A1:Z100")

如何以不同格式保存 Excel 工作簿?

using IronXL 的 SaveAs 方法保存工作簿:workbook.SaveAs("file.xlsx") 為 XLSX,或使用 SaveAsCsv()SaveAsJson() 為其他格式。

如何使用資料庫中的資料填充 Excel 表?

using IronXL 透過從資料庫提取資料並使用方法如 worksheet["A1"].Value = dataFromDatabase 將其設置到單元格中。

如何在 C# 中實現 Excel 表格的凍結窗格?

using IronXL 凍結工作表中的窗格:worksheet.FreezePanes(1, 1) 以鎖定頂行和最左列以便輕鬆導航。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

準備好開始了嗎?
Nuget 下載 2,150,290 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

仍在滾動嗎?

想要快速證明嗎? PM > Install-Package IronXL.Excel
運行一個範例 觀看您的資料成為試算表。