如何在 C# 中建立 Excel 文件

如何在不使用互通的情況下用 C# 建立 Excel 文件

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

學習如何使用 IronXL 在 C# 中產生 Excel 檔案——IronXL 是一個功能強大的 .NET Excel 庫,可以建立、讀取和編輯電子表格,而無需依賴 Microsoft Office。 本教學將透過逐步程式碼範例,引導您以程式設計方式建立 Excel 工作簿。

快速入門:一行簡單Excel工作簿建立

使用 IronXL 可以立即建立一個新的 Excel 檔案——只需選擇格式、新增工作表、設定任意儲存格值並儲存即可。 這是產生 XLSX 檔案的最快方法,它具有直覺的 API 調用,並且不會出現任何互通性問題。

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

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

    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 快速安裝
  • 免費用於開發。 來自$799許可證

如何快速建立並儲存Excel檔案?

透過 NuGet 安裝 IronXL直接下載 DLL 檔案

using IronXL;

// Create a new Excel workbook with XLSX format
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);

// Add a worksheet to the workbook
var workSheet = workBook.CreateWorkSheet("example_sheet");

// Set individual cell values using intuitive syntax
workSheet["A1"].Value = "Example";

// Set multiple cells at once using range syntax
workSheet["A2:A4"].Value = 5;

// Apply cell styling - set background color using hex code
workSheet["A5"].Style.SetBackgroundColor("#f0f0f0");

// Make text bold for better visibility
workSheet["A5:A6"].Style.Font.Bold = true;

// Add Excel formula to calculate sum
workSheet["A6"].Formula = "=SUM(A2:A4)";

// Calculate all formulas to show results
workSheet.EvaluateAll();

// Verify formula calculation worked correctly
if (workSheet["A6"].IntValue == 15) // Sum of three cells with value 5
{
    Console.WriteLine("Formula calculation successful!");
}

// Save the Excel file to disk
workBook.SaveAs("example_workbook.xlsx");
using IronXL;

// Create a new Excel workbook with XLSX format
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);

// Add a worksheet to the workbook
var workSheet = workBook.CreateWorkSheet("example_sheet");

// Set individual cell values using intuitive syntax
workSheet["A1"].Value = "Example";

// Set multiple cells at once using range syntax
workSheet["A2:A4"].Value = 5;

// Apply cell styling - set background color using hex code
workSheet["A5"].Style.SetBackgroundColor("#f0f0f0");

// Make text bold for better visibility
workSheet["A5:A6"].Style.Font.Bold = true;

// Add Excel formula to calculate sum
workSheet["A6"].Formula = "=SUM(A2:A4)";

// Calculate all formulas to show results
workSheet.EvaluateAll();

// Verify formula calculation worked correctly
if (workSheet["A6"].IntValue == 15) // Sum of three cells with value 5
{
    Console.WriteLine("Formula calculation successful!");
}

// Save the Excel file to disk
workBook.SaveAs("example_workbook.xlsx");
$vbLabelText   $csharpLabel

此程式碼示範了 IronXL 的主要功能:建立工作簿、新增工作表、設定儲存格值和樣式、使用公式以及儲存檔案。 WorkBook類別是所有 Excel 操作的入口點,而WorkSheet類別提供了操作單一工作表的方法。


步驟 1

1. 如何安裝 IronXL C# 函式庫?

使用 NuGet ( Install-Package IronXL ) 安裝 IronXL 庫,或直接下載 DLL 檔案


如何使用 NuGet 安裝 IronXL?

安裝 IronXL NuGet 套件有三種方法:

  1. Visual Studio 套件管理器
  2. 開發人員命令提示符
  3. 直接從 NuGet.org 下載

Visual Studio 安裝

Visual Studio 提供了 NuGet 套件管理器,方便使用者輕鬆安裝軟體套件。 透過"專案"功能表或在"解決方案資源管理器"中右鍵單擊項目來存取它。

Visual Studio 專案功能表中顯示

圖 3透過"專案"選單存取 NuGet 套件管理器

解決方案資源管理器上下文功能表顯示

圖 4解決方案資源管理器中的右鍵點選上下文選單


點選"管理 NuGet 套件"後,瀏覽至 IronXL.Excel 套件並進行安裝。


NuGet 套件管理器顯示 IronXL.Excel 套件已準備好安裝

圖 5透過 NuGet 套件管理器安裝 IronXL.Excel

開發者命令提示字元安裝

使用以下命令開啟軟體包管理器控制台:

Install-Package IronXL.Excel

直接下載安裝

  1. 導航至:https://www.nuget.org/packages/IronXL.Excel/
  2. 點選下載軟體包
  3. 雙擊下載的軟體包
  4. 重新載入 Visual Studio 項目

如何透過下載 DLL 檔案來安裝 IronXL?

直接從以下位置下載 IronXL:https://ironsoftware.com/csharp/excel/

IronXL 網站下載頁面顯示了安裝說明和下載按鈕

圖 6從官方網站下載 IronXL 庫

在項目中引用該庫:

  1. 在解決方案資源管理器中以滑鼠右鍵按一下解決方案。
  2. 選擇參考文獻
  3. 瀏覽並找到IronXL.dll
  4. 按一下"確定"

我們走吧!

現在,您可以開始探索 IronXL 強大的 Excel 處理功能了!


操作教學課程

2. 如何建立一個用於產生 Excel 的 ASP.NET 專案?

請依照下列步驟建立 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 表單模板

    ASP.NET 專案範本選擇,顯示 Web 表單選項

    圖 2Select Web Forms template

  7. 按一下"確定"

專案準備就緒後,安裝 IronXL 即可開始以程式設計方式建立 Excel 檔案。


3. 如何在 C# 中建立 Excel 工作簿?

使用 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);
$vbLabelText   $csharpLabel

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

3.1. 如何在我的工作簿中新增工作表?

新增工作表很簡單:

// 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");
$vbLabelText   $csharpLabel

一本練習冊包含一張或多張練習題。 每個工作表都由行和列組成,單元格位於行和列的交叉點。 使用CreateWorkSheet方法為工作簿新增工作表。


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

4.1. 如何手動設定儲存格值?

設定單一儲存格值時,可以使用類似 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
$vbLabelText   $csharpLabel

Cell.Value屬性接受多種資料類型,包括字串、數字、日期和布林值。 IronXL會根據資料類型自動格式化儲存格。

4.2. 如何動態設定儲存格值?

動態值設定非常適合數據驅動型應用:

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

字串插值( $"A{i}" )使動態引用儲存格變得容易。 Range索引器支援單一儲存格和範圍。

4.3. 如何從資料庫填充 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.Count; 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.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})";
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.Count; 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.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 資料、應用格式以及使用公式進行計算。 FormatString屬性可以像在 Excel 中一樣自訂數字格式。


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

5.1. 如何在 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");
    }
}
$vbLabelText   $csharpLabel

Style.SetBackgroundColor方法接受十六進位顏色代碼。 將背景顏色與字體顏色結合使用,打造專業美觀的電子表格。

5.2. 如何在 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
$vbLabelText   $csharpLabel

IronXL 支援多種邊框類型,包括細邊框、中等邊框、粗邊框、雙邊框、點狀邊框和虛線邊框。 邊框的每一邊都可以獨立設定樣式。


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

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();
$vbLabelText   $csharpLabel

Range類別提供了諸如Sum()Avg()Max()Min()之類的方法,用於快速計算。 對於更複雜的情況,可以使用Formula屬性直接設定 Excel 公式。


7. 如何設定工作表和列印屬性?

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

7.1. 如何配置工作表屬性?

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

// 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

工作表保護功能可防止意外修改,而凍結窗格功能可在捲動時保持重要行或列可見。

Excel 表格顯示了包含每月預算資料的凍結標題行

圖 7凍結的標題行在滾動時仍然可見

Excel 保護對話方塊要求輸入密碼才能修改受保護的工作表

圖 8密碼保護防止未經授權的編輯

7.2. 如何設定頁面和列印設定?

透過 IronXL 設定專業列印選項:

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

PrintSetup類別提供與 Excel 列印設定相符的全面列印配置選項。

Excel 列印預覽顯示橫向列印方向和 A4 紙張尺寸設定

圖 9橫向列印預覽及自訂邊距


8. 如何儲存我的 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);
$vbLabelText   $csharpLabel

IronXL 支援多種匯出格式,包括 XLSX、XLS、CSV、TSV 和 JSON。 SaveAs方法會自動根據檔案副檔名決定檔案格式。

概括

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

如需了解更多進階功能,請探索合併儲存格建立圖表。 準備好在生產中使用 IronXL 了嗎? 開始免費試用查看授權選項


教程快速訪問

Visual Studio 標誌

下載本教學的 C# 原始碼

用於建立 Excel 檔案的完整 C# 原始程式碼以 Visual Studio 專案檔案的形式提供。

下載

在 GitHub 上查看此教學。

此專案的原始碼可在 GitHub 上找到,提供 C# 和 VB.NET 兩種版本。

使用此程式碼,您可以在幾分鐘內輕鬆建立 Excel 檔案。此專案儲存為 Microsoft Visual Studio 項目,但與任何 .NET IDE 相容。

在 GitHub 上使用 C# 建立 Excel 文件
GitHub 標誌
API 文件圖示

請閱讀 IronXL API 參考文檔

探索 IronXL 的 API 參考,其中詳細介紹了所有功能、命名空間、類別、方法和屬性,以便在 .NET 中進行全面的 Excel 操作。

查看 API 參考

常見問題解答

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

您可以使用 IronXL 建立 Excel 文件,而無需使用 Interop。 IronXL 提供了一個簡單的 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 環境中執行。

如何安裝用於產生 Excel 表格的 C# 庫?

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

如何透過程式設計方式建立一個新的Excel工作簿?

使用 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 公式?

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

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

在 IronXL 中使用worksheet.ProtectSheet("YourPassword")保護工作表,以防止未經授權的修改。

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

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

如何將Excel工作簿儲存為不同的格式?

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

如何將資料庫中的資料匯入Excel表格?

使用 IronXL 從資料庫中獲取數據,並使用類似worksheet["A1"].Value = dataFromDatabase方法將其設定到單元格中,從而填充工作表。

如何使用 C# 在 Excel 表格中實作凍結窗格功能?

使用 IronXL 的worksheet.FreezePanes(1, 1)凍結工作表中的窗格,以鎖定頂行和最左側的列,以便更輕鬆地導覽。

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

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。

準備好開始了嗎?
Nuget 下載 1,802,965 | 版本: 2025.12 剛剛發布