如何在 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

IronXL 是一款強大的 C# 和 .NET Excel 程式庫,讓您能夠透過程式設計方式建立、讀取及編輯 XLSX 試算表——無需依賴 Microsoft Office 或 Interop。 它支援 .NET 8、.NET 9、.NET Core 及 .NET Framework,並可在 Windows、Linux、macOS、Azure 及 AWS 上運行。

本教學將引導您使用 C# 建立完整的 Excel 工作簿:設定儲存格值、套用格式、新增公式,以及匯出為 XLSX、CSV 等格式——並附有逐步的程式碼範例。

快速入門:建立 Excel 檔案 using IronXL 即可瞬間建立新的 Excel 檔案——只需選擇格式、新增工作表、設定任何儲存格值,然後儲存即可。 這是透過直觀的 API 呼叫生成 XLSX 檔案,且完全無需擔心互通性問題的最快速方式。

  1. using 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 Excel API,讓您能在 .NET 環境中以卓越的效能讀取、編輯及建立 Excel 試算表檔案。 與傳統方法不同,無需安裝 Microsoft Office 或使用 Excel Interop,使部署過程更為簡便且可靠。

IronXL 完全支援 .NET 9、.NET 8、.NET Core、.NET Framework、Xamarin、行動裝置、Linux、macOS 以及 Azure 環境。

IronXL 功能

  • 由我們的 .NET 開發團隊直接提供人工支援
  • 可透過 Microsoft Visual Studio 快速安裝
  • 開發用途免費。 授權來自 $999

如何快速建立並節省 Excel 檔案?

透過 NuGet 安裝 IronXL,或直接下載 DLL 檔案WorkBook 類別是您執行所有 Excel 操作的入口點,而 WorkSheet 類別則提供用於操作個別工作表的方法 — 完整的逐步操作指南將從下方的步驟 1 開始。


How Do I Install the IronXL C# Library?

透過 Visual Studio 中的 NuGet 套件管理員安裝 IronXL,或使用套件管理員主控台:

Install-Package IronXL.Excel

您可以透過"專案"選單,或在"解決方案總覽"中右鍵點擊您的專案,來存取 NuGet 套件管理員。

Visual Studio 專案選單中顯示的
圖 3 - 透過"專案"選單存取 NuGet 套件管理員

<img src="/img/tutorials/create-excel-file-net/right-click-solution-explorer.png" alt=""解決方案資源管理員"的右鍵選單顯示"管理 NuGet 套件"選項">
圖 4 - 解決方案資源管理員中的右鍵點擊快顯選單

在套件清單中搜尋 IronXl.Excel,然後點擊"安裝"。


NuGet 套件管理員顯示 IronXl.Excel 套件已準備就緒,可進行安裝
圖 5 - 透過 NuGet 套件管理員安裝 IronXl.Excel

或者,您可以直接下載 IronXL DLL,並透過"解決方案總覽">"參考項目">"瀏覽"選取 IronXL.dll 將其新增為專案的參考項目。

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

{i:(IronXL 無需安裝 Microsoft Office 或 Excel Interop — 它可在任何支援 .NET 的平台上運行,包括 Windows、Linux、macOS 及雲端環境。)}


如何設定我的 .NET 專案?

IronXL 可與任何類型的 .NET 專案配合使用 — 包括主控台應用程式、ASP.NET 網頁應用程式、API 或桌面工具。 以下範例使用 ASP.NET Web 應用程式,但此流程適用於所有專案範本。

請按照以下步驟建立一個 ASP.NET 網站:

  1. 開啟 Visual Studio
  2. 點擊"檔案">"新增專案"
  3. 在"專案類型"清單中,於 Visual C# 下方選取"Web"
  4. 選擇 ASP.NET Web 應用程式


    Visual Studio

    圖 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#?

using IronXL 建立新的 Excel 工作簿只需一行程式碼:

using IronXL;

// Create workbook with XLSX format (recommended for modern Excel)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);

// Alternative: Create legacy XLS format for older Excel versions
WorkBook legacyWorkbook = WorkBook.Create(ExcelFileFormat.XLS);
using IronXL;

// Create workbook with XLSX format (recommended for modern Excel)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);

// Alternative: Create legacy XLS format for older Excel versions
WorkBook legacyWorkbook = WorkBook.Create(ExcelFileFormat.XLS);
Imports IronXL

' Create workbook with XLSX format (recommended for modern Excel)
Private workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)

' Alternative: Create legacy XLS format for older Excel versions
Private legacyWorkbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)
$vbLabelText   $csharpLabel

Create 方法同時支援 XLS(Excel 97-2003)和 XLSX(Excel 2007+)格式。 建議使用 XLSX 格式,以獲得更佳的效能並縮小檔案大小。

  • XLSX:建議用於所有現代版 Excel(2007 版以上)—— 檔案較小,效能更佳
  • XLS:為與 Excel 97–2003 版本相容而保留的舊版格式

如何將工作表新增至工作簿?

新增工作表的步驟非常簡單:

// Create a worksheet with custom name for budget tracking
WorkSheet budgetSheet = workbook.CreateWorkSheet("2020 Budget");

// Add multiple worksheets for different purposes
WorkSheet salesSheet = workbook.CreateWorkSheet("Sales Data");
WorkSheet inventorySheet = workbook.CreateWorkSheet("Inventory");

// Access existing worksheet by name
WorkSheet existingSheet = workbook.GetWorkSheet("2020 Budget");
// Create a worksheet with custom name for budget tracking
WorkSheet budgetSheet = workbook.CreateWorkSheet("2020 Budget");

// Add multiple worksheets for different purposes
WorkSheet salesSheet = workbook.CreateWorkSheet("Sales Data");
WorkSheet inventorySheet = workbook.CreateWorkSheet("Inventory");

// Access existing worksheet by name
WorkSheet existingSheet = workbook.GetWorkSheet("2020 Budget");
' Create a worksheet with custom name for budget tracking
Dim budgetSheet As WorkSheet = workbook.CreateWorkSheet("2020 Budget")

' Add multiple worksheets for different purposes
Dim salesSheet As WorkSheet = workbook.CreateWorkSheet("Sales Data")
Dim inventorySheet As WorkSheet = workbook.CreateWorkSheet("Inventory")

' Access existing worksheet by name
Dim existingSheet As WorkSheet = workbook.GetWorkSheet("2020 Budget")
$vbLabelText   $csharpLabel

工作簿包含一個或多個工作表。 每個工作表由行與列組成,其交點處即為儲存格。 請使用 CreateWorkSheet 方法向工作簿新增工作表。

  • WorkBook.CreateWorkSheet(String):新增一個具有指定工作表名稱的工作表
  • WorkSheet:根據名稱擷取現有工作表
  • 工作表名稱在工作簿內必須是唯一的

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

如何手動設定儲存格值?

設定個別儲存格的值時,採用直觀的類似 Excel 語法:

// Set month names in first row for annual budget spreadsheet
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";

// Set different data types - IronXL handles conversion automatically
workSheet["A2"].Value = 1500.50m;  // Decimal for currency
workSheet["A3"].Value = DateTime.Now;  // Date values
workSheet["A4"].Value = true;  // Boolean values
// Set month names in first row for annual budget spreadsheet
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";

// Set different data types - IronXL handles conversion automatically
workSheet["A2"].Value = 1500.50m;  // Decimal for currency
workSheet["A3"].Value = DateTime.Now;  // Date values
workSheet["A4"].Value = true;  // Boolean values
' Set month names in first row for annual budget spreadsheet
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"

' Set different data types - IronXL handles conversion automatically
workSheet("A2").Value = 1500.50D ' Decimal for currency
workSheet("A3").Value = DateTime.Now ' Date values
workSheet("A4").Value = True ' Boolean values
$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 是一項常見的需求:

using System.Data;
using System.Data.SqlClient;
using IronXL;

// Database connection setup for retrieving sales data
string connectionString = @"Data Source=ServerName;Initial Catalog=SalesDB;Integrated Security=true";
string query = "SELECT ProductName, Quantity, UnitPrice, TotalSales FROM MonthlySales";

// Create DataSet to hold query results
DataSet salesData = new DataSet();

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
    // Fill DataSet with sales information
    adapter.Fill(salesData);
}

// Write headers for database columns
workSheet["A1"].Value = "Product Name";
workSheet["B1"].Value = "Quantity";
workSheet["C1"].Value = "Unit Price";
workSheet["D1"].Value = "Total Sales";

// Apply header formatting
workSheet["A1:D1"].Style.Font.Bold = true;
workSheet["A1:D1"].Style.SetBackgroundColor("#4472C4");
workSheet["A1:D1"].Style.Font.FontColor = "#FFFFFF";

// Populate Excel with database records
DataTable salesTable = salesData.Tables[0];
for (int row = 0; row < salesTable.Rows.Co/unt; row++)
{
    int excelRow = row + 2; // Start from row 2 (after headers)

    workSheet[$"A{excelRow}"].Value = salesTable.Rows[row]["ProductName"].ToString();
    workSheet[$"B{excelRow}"].Value = Convert.ToInt32(salesTable.Rows[row]["Quantity"]);
    workSheet[$"C{excelRow}"].Value = Convert.ToDecimal(salesTable.Rows[row]["UnitPrice"]);
    workSheet[$"D{excelRow}"].Value = Convert.ToDecimal(salesTable.Rows[row]["TotalSales"]);

    // Format currency columns
    workSheet[$"C{excelRow}"].FormatString = "$#,##0.00";
    workSheet[$"D{excelRow}"].FormatString = "$#,##0.00";
}

// Add summary row with formulas
int summaryRow = salesTable.Rows.Co/unt + 2;
workSheet[$"A{summaryRow}"].Value = "TOTAL";
workSheet[$"B{summaryRow}"].Formula = $"=SUM(B2:B{summaryRow-1})";
workSheet[$"D{summaryRow}"].Formula = $"=SUM(D2:D{summaryRow-1})";
using System.Data;
using System.Data.SqlClient;
using IronXL;

// Database connection setup for retrieving sales data
string connectionString = @"Data Source=ServerName;Initial Catalog=SalesDB;Integrated Security=true";
string query = "SELECT ProductName, Quantity, UnitPrice, TotalSales FROM MonthlySales";

// Create DataSet to hold query results
DataSet salesData = new DataSet();

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
    // Fill DataSet with sales information
    adapter.Fill(salesData);
}

// Write headers for database columns
workSheet["A1"].Value = "Product Name";
workSheet["B1"].Value = "Quantity";
workSheet["C1"].Value = "Unit Price";
workSheet["D1"].Value = "Total Sales";

// Apply header formatting
workSheet["A1:D1"].Style.Font.Bold = true;
workSheet["A1:D1"].Style.SetBackgroundColor("#4472C4");
workSheet["A1:D1"].Style.Font.FontColor = "#FFFFFF";

// Populate Excel with database records
DataTable salesTable = salesData.Tables[0];
for (int row = 0; row < salesTable.Rows.Co/unt; row++)
{
    int excelRow = row + 2; // Start from row 2 (after headers)

    workSheet[$"A{excelRow}"].Value = salesTable.Rows[row]["ProductName"].ToString();
    workSheet[$"B{excelRow}"].Value = Convert.ToInt32(salesTable.Rows[row]["Quantity"]);
    workSheet[$"C{excelRow}"].Value = Convert.ToDecimal(salesTable.Rows[row]["UnitPrice"]);
    workSheet[$"D{excelRow}"].Value = Convert.ToDecimal(salesTable.Rows[row]["TotalSales"]);

    // Format currency columns
    workSheet[$"C{excelRow}"].FormatString = "$#,##0.00";
    workSheet[$"D{excelRow}"].FormatString = "$#,##0.00";
}

// Add summary row with formulas
int summaryRow = salesTable.Rows.Co/unt + 2;
workSheet[$"A{summaryRow}"].Value = "TOTAL";
workSheet[$"B{summaryRow}"].Formula = $"=SUM(B2:B{summaryRow-1})";
workSheet[$"D{summaryRow}"].Formula = $"=SUM(D2:D{summaryRow-1})";
Imports System.Data
Imports System.Data.SqlClient
Imports IronXL

' Database connection setup for retrieving sales data
Dim connectionString As String = "Data Source=ServerName;Initial Catalog=SalesDB;Integrated Security=true"
Dim query As String = "SELECT ProductName, Quantity, UnitPrice, TotalSales FROM MonthlySales"

' Create DataSet to hold query results
Dim salesData As New DataSet()

Using connection As New SqlConnection(connectionString)
    Using adapter As New SqlDataAdapter(query, connection)
        ' Fill DataSet with sales information
        adapter.Fill(salesData)
    End Using
End Using

' Write headers for database columns
workSheet("A1").Value = "Product Name"
workSheet("B1").Value = "Quantity"
workSheet("C1").Value = "Unit Price"
workSheet("D1").Value = "Total Sales"

' Apply header formatting
workSheet("A1:D1").Style.Font.Bold = True
workSheet("A1:D1").Style.SetBackgroundColor("#4472C4")
workSheet("A1:D1").Style.Font.FontColor = "#FFFFFF"

' Populate Excel with database records
Dim salesTable As DataTable = salesData.Tables(0)
For row As Integer = 0 To salesTable.Rows.Count - 1
    Dim excelRow As Integer = row + 2 ' Start from row 2 (after headers)

    workSheet($"A{excelRow}").Value = salesTable.Rows(row)("ProductName").ToString()
    workSheet($"B{excelRow}").Value = Convert.ToInt32(salesTable.Rows(row)("Quantity"))
    workSheet($"C{excelRow}").Value = Convert.ToDecimal(salesTable.Rows(row)("UnitPrice"))
    workSheet($"D{excelRow}").Value = Convert.ToDecimal(salesTable.Rows(row)("TotalSales"))

    ' Format currency columns
    workSheet($"C{excelRow}").FormatString = "$#,##0.00"
    workSheet($"D{excelRow}").FormatString = "$#,##0.00"
Next

' Add summary row with formulas
Dim summaryRow As Integer = salesTable.Rows.Count + 2
workSheet($"A{summaryRow}").Value = "TOTAL"
workSheet($"B{summaryRow}").Formula = $"=SUM(B2:B{summaryRow - 1})"
workSheet($"D{summaryRow}").Formula = $"=SUM(D2:D{summaryRow - 1})"
$vbLabelText   $csharpLabel

此範例展示如何從資料庫讀取 Excel 資料、套用格式,以及使用公式進行計算。 NumberFormat 屬性可實現類似 Excel 的自訂數字格式設定。


如何對 Excel 儲存格套用格式?

如何在 Excel 中設定背景顏色?

儲存格樣式可提升可讀性與視覺吸引力:

// 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.FontColor = "#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.FontColor = "#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.FontColor = "#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 方法接受十六進位色彩代碼。 結合背景色與字體顏色,打造Professional外觀的試算表。

如何在 Excel 中建立邊框?

邊界有助於界定資料區域並改善結構:

using IronXL;
using IronXl.Styles;

// Create header border - thick bottom line to separate from data
workSheet["A1:L1"].Style.TopBorder.SetColor("#000000");
workSheet["A1:L1"].Style.TopBorder.Type = BorderType.Thick;
workSheet["A1:L1"].Style.BottomBorder.SetColor("#000000");
workSheet["A1:L1"].Style.BottomBorder.Type = BorderType.Thick;

// Add right border to last column
workSheet["L2:L11"].Style.RightBorder.SetColor("#000000");
workSheet["L2:L11"].Style.RightBorder.Type = BorderType.Medium;

// Create bottom border for data area
workSheet["A11:L11"].Style.BottomBorder.SetColor("#000000");
workSheet["A11:L11"].Style.BottomBorder.Type = BorderType.Medium;

// Apply complete border around summary section
var summaryRange = workSheet["A12:L12"];
summaryRange.Style.TopBorder.Type = BorderType.Double;
summaryRange.Style.BottomBorder.Type = BorderType.Double;
summaryRange.Style.LeftBorder.Type = BorderType.Thin;
summaryRange.Style.RightBorder.Type = BorderType.Thin;
summaryRange.Style.SetBorderColor("#0070C0"); // Blue borders
using IronXL;
using IronXl.Styles;

// Create header border - thick bottom line to separate from data
workSheet["A1:L1"].Style.TopBorder.SetColor("#000000");
workSheet["A1:L1"].Style.TopBorder.Type = BorderType.Thick;
workSheet["A1:L1"].Style.BottomBorder.SetColor("#000000");
workSheet["A1:L1"].Style.BottomBorder.Type = BorderType.Thick;

// Add right border to last column
workSheet["L2:L11"].Style.RightBorder.SetColor("#000000");
workSheet["L2:L11"].Style.RightBorder.Type = BorderType.Medium;

// Create bottom border for data area
workSheet["A11:L11"].Style.BottomBorder.SetColor("#000000");
workSheet["A11:L11"].Style.BottomBorder.Type = BorderType.Medium;

// Apply complete border around summary section
var summaryRange = workSheet["A12:L12"];
summaryRange.Style.TopBorder.Type = BorderType.Double;
summaryRange.Style.BottomBorder.Type = BorderType.Double;
summaryRange.Style.LeftBorder.Type = BorderType.Thin;
summaryRange.Style.RightBorder.Type = BorderType.Thin;
summaryRange.Style.SetBorderColor("#0070C0"); // Blue borders
Imports IronXL
Imports IronXl.Styles

' Create header border - thick bottom line to separate from data
workSheet("A1:L1").Style.TopBorder.SetColor("#000000")
workSheet("A1:L1").Style.TopBorder.Type = BorderType.Thick
workSheet("A1:L1").Style.BottomBorder.SetColor("#000000")
workSheet("A1:L1").Style.BottomBorder.Type = BorderType.Thick

' Add right border to last column
workSheet("L2:L11").Style.RightBorder.SetColor("#000000")
workSheet("L2:L11").Style.RightBorder.Type = BorderType.Medium

' Create bottom border for data area
workSheet("A11:L11").Style.BottomBorder.SetColor("#000000")
workSheet("A11:L11").Style.BottomBorder.Type = BorderType.Medium

' Apply complete border around summary section
Dim summaryRange = workSheet("A12:L12")
summaryRange.Style.TopBorder.Type = BorderType.Double
summaryRange.Style.BottomBorder.Type = BorderType.Double
summaryRange.Style.LeftBorder.Type = BorderType.Thin
summaryRange.Style.RightBorder.Type = BorderType.Thin
summaryRange.Style.SetBorderColor("#0070C0") ' Blue borders
$vbLabelText   $csharpLabel

IronXL 支援多種邊框類型,包括細線、中線、粗線、雙線、點線及虛線。 每個邊框邊緣皆可獨立設定樣式。


How Do I Use Excel Formulas in C#?

IronXL 提供強大的公式支援與自動計算功能:

// 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
workSheet.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
workSheet.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
workSheet.EvaluateAll()
$vbLabelText   $csharpLabel

Range 類別提供 MaxMin 等方法,用於快速計算。 對於更複雜的場景,請使用 Formula 屬性直接設定 Excel 公式。

{t:(在處理範圍時,建議優先使用 IronXL 內建的 .Max().Min() 方法,而非原始公式字串 — 這些方法具備類型安全性,可避免公式語法錯誤。)}


如何設定工作表與PRINT屬性?

using IronXL 來保護個別工作表、凍結列與欄,以及設定列印格式選項。

如何設定工作表屬性?

保護工作表並控制檢視選項:

// Protect worksheet with password to prevent unauthorized changes
workSheet.ProtectSheet("SecurePassword123");

// Freeze panes to keep headers visible while scrolling
workSheet.CreateFreezePane(0, 1); // Freeze first row
// workSheet.CreateFreezePane(1, 1); // Freeze first row and column

// Set worksheet visibility options
workSheet.ViewState = WorkSheetViewState.Visible; // or Hidden, VeryHidden

// Configure gridlines and headers
workSheet.ShowGridLines = true;
workSheet.ShowRowColHeaders = true;

// Set zoom level for better viewing
workSheet.Zoom = 85; // 85% zoom
// Protect worksheet with password to prevent unauthorized changes
workSheet.ProtectSheet("SecurePassword123");

// Freeze panes to keep headers visible while scrolling
workSheet.CreateFreezePane(0, 1); // Freeze first row
// workSheet.CreateFreezePane(1, 1); // Freeze first row and column

// Set worksheet visibility options
workSheet.ViewState = WorkSheetViewState.Visible; // or Hidden, VeryHidden

// Configure gridlines and headers
workSheet.ShowGridLines = true;
workSheet.ShowRowColHeaders = true;

// Set zoom level for better viewing
workSheet.Zoom = 85; // 85% zoom
' Protect worksheet with password to prevent unauthorized changes
workSheet.ProtectSheet("SecurePassword123")

' Freeze panes to keep headers visible while scrolling
workSheet.CreateFreezePane(0, 1) ' Freeze first row
' workSheet.CreateFreezePane(1, 1); // Freeze first row and column

' Set worksheet visibility options
workSheet.ViewState = WorkSheetViewState.Visible ' or Hidden, VeryHidden

' Configure gridlines and headers
workSheet.ShowGridLines = True
workSheet.ShowRowColHeaders = True

' Set zoom level for better viewing
workSheet.Zoom = 85 ' 85% zoom
$vbLabelText   $csharpLabel

工作表保護功能可防止意外修改,而凍結區塊功能則能在捲動時保持重要列或欄位始終可見。

Frozen Panes
圖 7 - 捲動時固定頂部行仍保持可見

Excel 保護對話方塊,要求輸入密碼才能修改受保護的工作表
圖 8 - 密碼保護可防止未經授權的編輯

如何設定頁面與列印設定?

透過 IronXL 設定 Professional 列印選項:

using IronXl.Printing;

// Define print area to exclude empty cells
workSheet.SetPrintArea("A1:L12");

// Configure page orientation for wide data
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape;

// Set paper size for standard printing
workSheet.PrintSetup.PaperSize = PaperSize.A4;

// Adjust margins for better layout (in inches)
workSheet.PrintSetup.LeftMargin = 0.5;
workSheet.PrintSetup.RightMargin = 0.5;
workSheet.PrintSetup.TopMargin = 0.75;
workSheet.PrintSetup.BottomMargin = 0.75;

// Configure header and footer
workSheet.PrintSetup.HeaderMargin = 0.3;
workSheet.PrintSetup.FooterMargin = 0.3;

// Scale to fit on one page
workSheet.PrintSetup.FitToPage = true;
workSheet.PrintSetup.FitToHeight = 1;
workSheet.PrintSetup.FitToWidth = 1;

// Add print headers/footers
workSheet.Header.Center = "Monthly Budget Report";
workSheet.Footer.Left = DateTime.Now.ToShortDateString();
workSheet.Footer.Right = "Page &P of &N"; // Page numbering
using IronXl.Printing;

// Define print area to exclude empty cells
workSheet.SetPrintArea("A1:L12");

// Configure page orientation for wide data
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape;

// Set paper size for standard printing
workSheet.PrintSetup.PaperSize = PaperSize.A4;

// Adjust margins for better layout (in inches)
workSheet.PrintSetup.LeftMargin = 0.5;
workSheet.PrintSetup.RightMargin = 0.5;
workSheet.PrintSetup.TopMargin = 0.75;
workSheet.PrintSetup.BottomMargin = 0.75;

// Configure header and footer
workSheet.PrintSetup.HeaderMargin = 0.3;
workSheet.PrintSetup.FooterMargin = 0.3;

// Scale to fit on one page
workSheet.PrintSetup.FitToPage = true;
workSheet.PrintSetup.FitToHeight = 1;
workSheet.PrintSetup.FitToWidth = 1;

// Add print headers/footers
workSheet.Header.Center = "Monthly Budget Report";
workSheet.Footer.Left = DateTime.Now.ToShortDateString();
workSheet.Footer.Right = "Page &P of &N"; // Page numbering
Imports IronXl.Printing

' Define print area to exclude empty cells
workSheet.SetPrintArea("A1:L12")

' Configure page orientation for wide data
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape

' Set paper size for standard printing
workSheet.PrintSetup.PaperSize = PaperSize.A4

' Adjust margins for better layout (in inches)
workSheet.PrintSetup.LeftMargin = 0.5
workSheet.PrintSetup.RightMargin = 0.5
workSheet.PrintSetup.TopMargin = 0.75
workSheet.PrintSetup.BottomMargin = 0.75

' Configure header and footer
workSheet.PrintSetup.HeaderMargin = 0.3
workSheet.PrintSetup.FooterMargin = 0.3

' Scale to fit on one page
workSheet.PrintSetup.FitToPage = True
workSheet.PrintSetup.FitToHeight = 1
workSheet.PrintSetup.FitToWidth = 1

' Add print headers/footers
workSheet.Header.Center = "Monthly Budget Report"
workSheet.Footer.Left = DateTime.Now.ToShortDateString()
workSheet.Footer.Right = "Page &P of &N" ' Page numbering
$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:用於記憶體內輸出 — 適用於網頁下載或雲端儲存

摘要

本教學示範了如何使用 IronXL,在不依賴 Microsoft Office 的情況下,透過 C# 建立 Excel 檔案。 您已學習了 Excel 的基本操作,包括工作簿建立、儲存格操作、格式設定、公式使用以及各種儲存選項。 IronXL 直觀的 API 讓 .NET 開發人員能輕鬆實現 Excel 自動化

若需更進階的功能,請探索合併儲存格建立圖表。 準備好在生產環境中使用 IronXL 了嗎? 立即開始免費試用查看授權方案

接下來該做什麼?

既然您現在已經可以透過 C# 建立 Excel 檔案,不妨進一步探索這些相關的 IronXL 功能:

WorkBook``WorkSheet``WorkBook.Create``CreateWorkSheet``CreateWorkSheet("name")``GetWorkSheet("name")``Cell.Value``$"A{i}"``Range``FormatString``Style.SetBackgroundColor``Range``Sum()``Avg()``Max()``Min()``Formula``PrintSetup``SaveAs

常見問題

如何在不使用 Interop 的情況下,透過 C# 建立 Excel 檔案?

您可以使用 IronXL 在不需 Interop 的情況下建立 Excel 檔案,該工具提供一個簡單的 API: WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX)。此方法適用於任何 .NET 平台,無需安裝 Microsoft Office。

using C# 建立 Excel 檔案支援哪些平台?

IronXL 支援在 .NET 10、.NET 9、.NET 8、.NET Core 及 .NET Framework 4.6.2+ 環境下建立 Excel 檔案,並可在 Windows、macOS、Linux、Docker、Azure 及 AWS 環境中運行。

如何安裝用於生成 Excel 的 C# 函式庫?

請透過 Visual Studio 中的 NuGet 套件管理員安裝 IronXL,使用指令 PM> Install-Package IronXL.Excel,或直接從 NuGet.org 下載。

如何透過程式碼建立新的 Excel 工作簿?

using IronXL 建立工作簿, WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX),接著使用 workbook.CreateWorkSheet("SheetName").

如何使用 C# 在 Excel 試算表中設定儲存格值?

使用直觀的語法在 IronXL 中設定儲存格值: worksheet["A1"].Value = "Hello World" 或設定範圍: worksheet["A1:A10"].Value = 100.

我可以透過程式設計方式對 Excel 儲存格套用格式嗎?

是的,IronXL 支援全面的格式設定,包括背景顏色(cell.Style.SetBackgroundColor("#FF0000"))、邊框、字型及數字格式。

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

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

如何使用密碼保護 Excel 試算表?

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

如何設定 Excel 檔案的 PRINT 設定?

using IronXL 的 PrintSetup 設定列印屬性: worksheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape 以及 worksheet.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)共同將公司發展為擁有 50 多名員工的企業,服務對象包括 NASA、特斯拉(Tesla)及全球政府機構。

雅各布於曼徹斯特大學(1998–2001)取得土木工程一等榮譽工程學士學位(BEng)。他在 1999 年於倫敦創立首家軟體公司,並於 2005 年開發出首批 .NET 元件,此後專注於解決微軟生態系統中的複雜問題。

其旗艦產品 IronPDF 與 Iron Suite .NET 函式庫在全球已累積超過 3,000 萬次 NuGet 安裝,其基礎程式碼持續驅動著全球廣泛使用的開發者工具。憑藉 25 年商業經驗與 41 年程式設計專業,雅各持續致力於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領導者。

準備開始了嗎?
Nuget 下載 2,052,917 | 版本: 2026.6 just released
Still Scrolling Icon

還在捲動嗎?

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