How to Create Excel Files in C# Without Interop
學習如何使用 IronXL 在 C# 中生成 Excel 文件——一個強大的 .NET Excel 庫,可創建、閱讀和編輯電子表格,而無需 Microsoft Office 依賴。 本詳細教程通過代碼示例逐步帶您構建 Excel 工作簿的流程。
作為標題:2(快速入門:簡單的一行 Excel 工作簿創建)
使用 IronXL 快速生成一個新的 Excel 文件——只需選擇一種格式、添加工作表、設置任何單元格值並保存。 這是通過直觀的 API 調用和零 Interop 煩惱來生成 XLSX 文件的最快方法。
Get started making PDFs with NuGet now:
Install IronXL with NuGet Package Manager
Copy and run this code snippet.
WorkBook book = IronXL.WorkBook.Create(IronXL.ExcelFileFormat.XLSX); book.CreateWorkSheet("Sheet1")["A1"].Value = "Hello World"; book.SaveAs("MyFile.xlsx");Deploy to test on your live environment
class="tutorial-segment-title">概覽
最小工作流程(5 步)
- 下載 C# 庫以創建 Excel 和 CSV 文件
- 創建 ASP.NET 項目 Web 應用程序
- 使用 IronXL 創建 Excel 工作簿
- 設置 Excel 工作表中的單元格值
- 應用格式和設定背景顏色
- 在單元格中使用公式
- 設置工作表和打印屬性
- 保存您的 Excel 工作簿
什麼是 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 文件?
Install IronXL via NuGet or 直接下載 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");
Imports IronXL
' Create a new Excel workbook with XLSX format
Private workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
' Add a worksheet to the workbook
Private workSheet = workBook.CreateWorkSheet("example_sheet")
' Set individual cell values using intuitive syntax
Private workSheet("A1").Value = "Example"
' Set multiple cells at once using range syntax
Private 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 Then ' Sum of three cells with value 5
Console.WriteLine("Formula calculation successful!")
End If
' Save the Excel file to disk
workBook.SaveAs("example_workbook.xlsx")
此代碼顯示了 IronXL 的主要功能:創建工作簿、添加工作表、設置單元格值和樣式、使用公式以及保存文件。 The WorkBook class serves as your entry point for all Excel operations, while the WorkSheet class provides methods to manipulate individual sheets.
class="tutorial-segment-title">步驟 1
1. 如何安裝 IronXL C# 庫?
使用 NuGet 安裝 IronXL 庫(Install-Package IronXL)或通過 直接下載 DLL。
立即開始在您的項目中使用 IronXL 並免費試用。
如何使用 NuGet 安裝 IronXL?
有三種方式安裝 IronXL 的 NuGet 包:
- Visual Studio 包管理器
- 開發者命令提示符
- 從 NuGet.org 直接下載
Visual Studio 安裝
Visual Studio 提供了 NuGet 包管理器來輕鬆安裝包。 可以通過項目菜單或在解決方案資源管理器中右鍵點擊您的項目來訪問它。
單擊管理 NuGet 包後,瀏覽以找到 IronXL.Excel 包並進行安裝。
開發者命令提示符安裝
在包管理器控制台中使用以下命令:
Install-Package IronXL.Excel
直接下載安裝
- 瀏覽到:https://www.nuget.org/packages/IronXL.Excel/
- 點擊下載包
- 雙擊下載的包
- 重新加載您的 Visual Studio 項目
如何通過下載 DLL 來安裝 IronXL?
直接從以下地址下載 IronXL:https://ironsoftware.com/csharp/excel/
在您的項目中引用該庫:
- 在解決方案資源管理器中右鍵單擊解決方案
- 選擇引用
- 瀏覽找到 IronXL.dll 庫
- 點擊確定
我們開始吧!
現在您可以開始探索 IronXL 強大的 Excel 處理功能!
class="tutorial-segment-title">如何使用教程
2. 如何為 Excel 生成創建 ASP.NET 項目?
按以下步驟創建 ASP.NET 網站:
- 打開Visual Studio
- 點擊文件 > 新建項目
- 在項目類型列表中,選擇 Visual C# 下的 Web
-
選擇 ASP.NET Web 應用程序
圖 1 – 創建新的 ASP.NET 項目
- 點擊確定
-
選擇 Web Forms 模板
圖 2 – *選擇 Web Forms 模板*
- 點擊確定
一旦您的項目準備好,安裝 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);
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)
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");
' 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")
一個工作簿可以包含一個或多個工作表。 每個工作表由行和列組成,它們的交集處是單元格。 使用 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
' 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
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
' 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
字符串插值($"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})";
Imports System.Data
Imports System.Data.SqlClient
Imports IronXL
' Database connection setup for retrieving sales data
Private connectionString As String = "Data Source=ServerName;Initial Catalog=SalesDB;Integrated Security=true"
Private query As String = "SELECT ProductName, Quantity, UnitPrice, TotalSales FROM MonthlySales"
' Create DataSet to hold query results
Private 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 row
' 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})"
此示例演示如何從數據庫讀取 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");
}
}
' 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
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
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
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();
' 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()
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
' 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
工作表保護可防止意外修改,而凍結窗格則可在滾動時保持重要行或列可見。
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
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
PrintSetup 類提供了與 Excel 的打印設置匹配的完整打印配置選項。
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);
' 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)
IronXL 支持多種導出格式,包括 XLSX、XLS、CSV、TSV 和 JSON。 SaveAs 方法根據文件擴展名自動確定格式。
總結
本教程演示了如何使用 IronXL 在 C# 中創建無需 Microsoft Office 依賴的 Excel 文件。 您學習了從工作簿創建、單元格操作、格式設置、使用公式和各種保存選項的基本 Excel 操作。 IronXL 的直觀 API 使 .NET 開發者可以輕鬆進行 Excel 自動化。
For more advanced features, explore merging cells, and creating charts. 準備好使用 IronXL 上線嗎? Start your free trial or 查看許可證選項。
class="tutorial-segment-title">教程快速訪問
在 GitHub 上探索該教程
該項目的源代碼可在 GitHub 上以 C# 和 VB.NET 獲取。
使用此代碼作為一種便捷方式來快速啟動 Excel 文件的創建。該項目已保存為 Microsoft Visual Studio 項目但可與任何 .NET IDE 兼容。
在 GitHub 上用 C# 創建 Excel 文件閱讀 IronXL API 參考
探索 IronXL 的 API 參考,詳細描述了所有功能、命名空間、類別、方法和屬性,以進行全面的 Excel 操作。
查看 API 參考常見問題解答
如何在不使用 Interop 的情況下在 C# 中創建 Excel 檔案?
您可以使用 IronXL 創建不需要 Interop 的 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?
在 Visual Studio 中通過 NuGet 包管理器安裝 IronXL,使用命令 PM> Install-Package IronXL.Excel,或直接從 nuget.org 下載。
我如何以程式化方式創建一個新的 Excel 工作簿?
使用 IronXL 創建一個工作簿:WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX),然後使用 workbook.CreateWorkSheet("SheetName") 添加工作表。
我如何在 Excel 工作表中設置單元格值,使用 C#?
使用 IronXL 設置單元格值,語法簡單:worksheet["A1"].Value = "Hello World" 或設置範圍:worksheet["A1:A10"].Value = 100。
我可以以編程方式為 Excel 單元格應用格式嗎?
是的,IronXL 支持全面的格式設置,包括背景顏色(cell.Style.SetBackgroundColor("#FF0000"))、邊框、字體和數字格式。
我如何在 C# 中使用 Excel 公式?
使用 IronXL 的公式屬性應用公式:worksheet["A1"].Formula = "=SUM(B1:B10)",或使用內置方法如 range.Sum()、range.Avg()。
我如何用密碼保護 Excel 工作表?
使用 IronXL 保護工作表,代碼為 worksheet.ProtectSheet("YourPassword"),以防止未授權的修改。
我如何配置 Excel 檔案的打印設置?
使用 IronXL 的打印設置:worksheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape 和 worksheet.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) 以便鎖定頂部行和左側列,便於導航。








