跳過到頁腳內容
使用 IRONXL

如何在 C# 中使用 IronXL 創建 Excel 生成報告

在 C# 中創建 Excel 報告是現代商業和 .NET 應用程式中的基本需求。 無論您正在生成財務報告、銷售分析還是庫存儀表板,自動化創建 Excel 檔案和 Excel 試算表的過程都可以節省大量的人工時間並減少錯誤。

IronXL 為開發人員提供了一個強大而直觀的解決方案,可以在 C 中創建 Excel 報告,而無需使用 Microsoft Office、MS Excel 或傳統的互操作依賴性。 不像依賴於 Excel 應用程式的 OLE 自動化或其他方法,IronXL 能夠直接在代碼中生成 Excel 工作簿和 Excel 數據,只需一行代碼即可完成。 在本指南中,我們將教您如何使用 IronXl 創建 Excel 報告,提供易於遵循的範例代碼,您可以輕鬆應用到您自己的項目中!

什麼是 IronXL 以及為什麼使用它來生成 Excel 檔案?

IronXL 是一個 .NET Excel 庫,允許開發人員從 C# 或 Visual Basic 源代碼直接創建 Excel、讀取 Excel 試算表和操作 Excel 檔案。 與依賴完整 Excel 應用程式或透過 Open XML SDK 逆向工程的方法不同,IronXL 可以在不需要 Excel 安裝或第三方依賴的情況下,在 Windows、Linux、macOS 和雲環境中運作。 這使其非常適合於基於 .NET Core 或 .NET Framework 的服務器端 Excel 報告、自動化工作流程和 Web 應用程式。

對於從手動 Excel 流程、舊版庫或需要瀏覽各種 XML 名稱空間的 Open XML 生產力工具工作流程過渡的團隊,IronXL 提供了一個直觀的 API。 它支持遺留的 XLS 檔案和現代的 XLSX 檔案,後者本質上是包含 XML 檔案和各種資料夾的 ZIP 檔案。 無論您是想生成新的 Excel 工作簿、操作多個試算表還是從外部代碼加載 Excel 數據,IronXL 在不需要了解底層格式的情況下極大地簡化了這一過程。

開始使用 IronXL 創建 Excel 檔案

設置 IronXL 來創建 Excel 報告只需幾分鐘。 在 Visual Studio 中透過 NuGet 套件管理器安裝此庫:

Install-Package IronXL.Excel

立即下載 IronXL,開始自動化生成您的 Excel 報告。

安裝完成後,創建您的第一個 Excel 報告只需幾行代碼:

using IronXL;
// Create a new Excel workbook for reports
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add a worksheet for the report
WorkSheet reportSheet = workBook.CreateWorkSheet("Monthly Report");
// Add a title
reportSheet["A1"].Value = "Sales Report - January 2024";
reportSheet["A1"].Style.Font.Bold = true;
// Save the Excel report
workBook.SaveAs("MonthlyReport.xlsx");
using IronXL;
// Create a new Excel workbook for reports
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add a worksheet for the report
WorkSheet reportSheet = workBook.CreateWorkSheet("Monthly Report");
// Add a title
reportSheet["A1"].Value = "Sales Report - January 2024";
reportSheet["A1"].Style.Font.Bold = true;
// Save the Excel report
workBook.SaveAs("MonthlyReport.xlsx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

此代碼創建了一個帶有格式化標題的新 Excel 報告檔案。 熟悉的單元格引用語法(reportSheet["A1"])使開發人員可以像手動操作 Excel 一樣,輕鬆指定數據應出現的位置。

輸出

如何使用 IronXL 在 C# 中創建 Excel 報告:圖 1 - 範例 Excel 輸出

從多個來源加載數據

現實世界的 Excel 報告很少使用靜態數據。 IronXL 擅長整合各種格式的 Excel 數據、API、新的 DataTable 來源,甚至是幾個不同的 XML 檔案。 這使其非常適合於伺服器端或 Web 應用中動態的 C# Excel 報告生成。

數據庫整合

For database-driven Excel reports, IronXL seamlessly works with ADO.NET DataTables:

using System.Data;
using System.Data.SqlClient;
// Fetch data from database
string connectionString = "Server=localhost;Database=Sales;Integrated Security=true;";
DataTable salesData = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
    SqlDataAdapter adapter = new SqlDataAdapter(
        "SELECT ProductName, Quantity, Revenue FROM MonthlySales", conn);
    adapter.Fill(salesData);
}
// Create Excel report from DataTable
WorkBook workBook = WorkBook.Create();
WorkSheet sheet = workBook.CreateWorkSheet("Sales Data");
// Add headers
sheet["A1"].Value = "Product";
sheet["B1"].Value = "Quantity";  
sheet["C1"].Value = "Revenue";
// Populate data
int row = 2;
foreach (DataRow dataRow in salesData.Rows)
{
    sheet[$"A{row}"].Value = dataRow["ProductName"];
    sheet[$"B{row}"].Value = dataRow["Quantity"];
    sheet[$"C{row}"].Value = dataRow["Revenue"];
    row++;
}
using System.Data;
using System.Data.SqlClient;
// Fetch data from database
string connectionString = "Server=localhost;Database=Sales;Integrated Security=true;";
DataTable salesData = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
    SqlDataAdapter adapter = new SqlDataAdapter(
        "SELECT ProductName, Quantity, Revenue FROM MonthlySales", conn);
    adapter.Fill(salesData);
}
// Create Excel report from DataTable
WorkBook workBook = WorkBook.Create();
WorkSheet sheet = workBook.CreateWorkSheet("Sales Data");
// Add headers
sheet["A1"].Value = "Product";
sheet["B1"].Value = "Quantity";  
sheet["C1"].Value = "Revenue";
// Populate data
int row = 2;
foreach (DataRow dataRow in salesData.Rows)
{
    sheet[$"A{row}"].Value = dataRow["ProductName"];
    sheet[$"B{row}"].Value = dataRow["Quantity"];
    sheet[$"C{row}"].Value = dataRow["Revenue"];
    row++;
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

該方法直接從 SQL Server 將銷售數據加載到您的 Excel 報告中。 DataTable 整合意味著您可以在不進行修改的情況下使用現有的數據訪問代碼。 對於更復雜的場景,查看如何從 SQL 數據庫加載 Excel

與集合一起工作

對於內存中數據、來自 API 響應的 Excel 數據或新的 DataTable,集合可以輕鬆填充 Excel 試算表,而無需 Microsoft Excel 或第三方依賴:

var salesRecords = new List<SalesRecord>
{
    new SalesRecord { Product = "Widget A", Units = 150, Price = 29.99m },
    new SalesRecord { Product = "Widget B", Units = 82, Price = 49.99m }
};
// Convert collection to Excel
for (int i = 0; i < salesRecords.Count; i++)
{
    sheet[$"A{i+2}"].Value = salesRecords[i].Product;
    sheet[$"B{i+2}"].Value = salesRecords[i].Units;
    sheet[$"C{i+2}"].Value = salesRecords[i].Price;
}
var salesRecords = new List<SalesRecord>
{
    new SalesRecord { Product = "Widget A", Units = 150, Price = 29.99m },
    new SalesRecord { Product = "Widget B", Units = 82, Price = 49.99m }
};
// Convert collection to Excel
for (int i = 0; i < salesRecords.Count; i++)
{
    sheet[$"A{i+2}"].Value = salesRecords[i].Product;
    sheet[$"B{i+2}"].Value = salesRecords[i].Units;
    sheet[$"C{i+2}"].Value = salesRecords[i].Price;
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

此方法允許在 .NET 應用中直接以 C# 創建 Excel 報告,使生成多個試算表或 XLSX 檔案的過程比手動 OLE 自動化或逆向工程 XML 檔案更簡單。

輸出

如何使用 IronXL 在 C# 中創建 Excel 報告:圖 2 - 來自數據輸出的範例試算表

格式化專業的 Excel 報告

僅有原始數據並不能構成專業報告。 IronXL 提供了全面的單元格式選項,以創建精緻的、適合業務使用的 Excel 檔案。 以下代碼顯示如何使用 IronXL 來輕鬆格式化:

using IronXL;
using IronXL.Styles;
class Program
{
    static void Main(string[] args)
    {
        // Create a new workbook
        var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        // Add a new worksheet
        var sheet = workbook.CreateWorkSheet("MySheet");
        // Add header values
        sheet["A1"].Value = "Product";
        sheet["B1"].Value = "Quantity";
        sheet["C1"].Value = "Price";
        // Add sample data rows
        sheet["A2"].Value = "Laptop";
        sheet["B2"].Value = 5;
        sheet["C2"].Value = 1299.99;
        sheet["A3"].Value = "Headphones";
        sheet["B3"].Value = 15;
        sheet["C3"].Value = 199.50;
        sheet["A4"].Value = "Keyboard";
        sheet["B4"].Value = 10;
        sheet["C4"].Value = 89.99;
        sheet["A5"].Value = "Monitor";
        sheet["B5"].Value = 7;
        sheet["C5"].Value = 249.00;
        // Header formatting
        var headerRange = sheet["A1:C1"];
        headerRange.Style.Font.Bold = true;
        headerRange.Style.SetBackgroundColor("#4472C4");
        headerRange.Style.Font.Color = "#FFFFFF";
        headerRange.Style.BottomBorder.Type = BorderType.Thick;
        // Number formatting for currency  
        sheet["C:C"].FormatString = "$#,##0.00";
        // Alternating row colors for readability
        for (int row = 2; row <= 10; row++)
        {
            if (row % 2 == 0)
            {
                sheet[$"A{row}:C{row}"].Style.SetBackgroundColor("#F2F2F2");
            }
        }
        // Column width adjustment
        sheet.Columns[0].Width = 15 * 256; // Width in 1/256th of character width
        sheet.Columns[2].Width = 12 * 256;
        // Add borders around data
        var dataRange = sheet["A1:C10"];
        dataRange.Style.TopBorder.Type = BorderType.Thin;
        dataRange.Style.RightBorder.Type = BorderType.Thin;
        dataRange.Style.BottomBorder.Type = BorderType.Thin;
        dataRange.Style.LeftBorder.Type = BorderType.Thin;
        // Save the workbook to a file
        workbook.SaveAs("MyWorkbook.xlsx");
    }
}
using IronXL;
using IronXL.Styles;
class Program
{
    static void Main(string[] args)
    {
        // Create a new workbook
        var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        // Add a new worksheet
        var sheet = workbook.CreateWorkSheet("MySheet");
        // Add header values
        sheet["A1"].Value = "Product";
        sheet["B1"].Value = "Quantity";
        sheet["C1"].Value = "Price";
        // Add sample data rows
        sheet["A2"].Value = "Laptop";
        sheet["B2"].Value = 5;
        sheet["C2"].Value = 1299.99;
        sheet["A3"].Value = "Headphones";
        sheet["B3"].Value = 15;
        sheet["C3"].Value = 199.50;
        sheet["A4"].Value = "Keyboard";
        sheet["B4"].Value = 10;
        sheet["C4"].Value = 89.99;
        sheet["A5"].Value = "Monitor";
        sheet["B5"].Value = 7;
        sheet["C5"].Value = 249.00;
        // Header formatting
        var headerRange = sheet["A1:C1"];
        headerRange.Style.Font.Bold = true;
        headerRange.Style.SetBackgroundColor("#4472C4");
        headerRange.Style.Font.Color = "#FFFFFF";
        headerRange.Style.BottomBorder.Type = BorderType.Thick;
        // Number formatting for currency  
        sheet["C:C"].FormatString = "$#,##0.00";
        // Alternating row colors for readability
        for (int row = 2; row <= 10; row++)
        {
            if (row % 2 == 0)
            {
                sheet[$"A{row}:C{row}"].Style.SetBackgroundColor("#F2F2F2");
            }
        }
        // Column width adjustment
        sheet.Columns[0].Width = 15 * 256; // Width in 1/256th of character width
        sheet.Columns[2].Width = 12 * 256;
        // Add borders around data
        var dataRange = sheet["A1:C10"];
        dataRange.Style.TopBorder.Type = BorderType.Thin;
        dataRange.Style.RightBorder.Type = BorderType.Thin;
        dataRange.Style.BottomBorder.Type = BorderType.Thin;
        dataRange.Style.LeftBorder.Type = BorderType.Thin;
        // Save the workbook to a file
        workbook.SaveAs("MyWorkbook.xlsx");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

這些格式選項將基本數據轉化為專業報告。 The style API covers everything from fonts and colors to borders and alignment, giving complete control over the Excel report appearance. 對於高級格式需求,探索條件格式化以自動突出顯示重要數據。

如何使用 IronXL 在 C# 中創建 Excel 報告:圖 3 - 已格式化的 Excel 輸出

使用公式來進行動態 Excel 報告計算

Excel 的威力在於其公式,IronXL 完全支持Excel 公式的創建

// Add formula for row totals
sheet["D1"].Value = "Total";
sheet["D2"].Formula = "=B2*C2";
// Copy formula down the column
for (int row = 3; row <= 10; row++)
{
    sheet[$"D{row}"].Formula = $"=B{row}*C{row}";
}
// Add summary formulas
sheet["A12"].Value = "Summary";
sheet["B12"].Formula = "=SUM(B2:B10)";
sheet["C12"].Formula = "=AVERAGE(C2:C10)";
sheet["D12"].Formula = "=SUM(D2:D10)";
// Add formula for row totals
sheet["D1"].Value = "Total";
sheet["D2"].Formula = "=B2*C2";
// Copy formula down the column
for (int row = 3; row <= 10; row++)
{
    sheet[$"D{row}"].Formula = $"=B{row}*C{row}";
}
// Add summary formulas
sheet["A12"].Value = "Summary";
sheet["B12"].Formula = "=SUM(B2:B10)";
sheet["C12"].Formula = "=AVERAGE(C2:C10)";
sheet["D12"].Formula = "=SUM(D2:D10)";
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

公式支持包括所有標準的 Excel 函數,如 SUM、AVERAGE、IF、VLOOKUP 等。 IronXL 自動處理公式依賴項和計算順序,使包含復雜計算的 Excel 報告生成變得簡單明瞭。 了解更多有關 IronXL 中的數學函數

如何使用 IronXL 在 C# 中創建 Excel 報告:圖 4 - 含公式的範例輸出

基於模板的報告

對於持續的 Excel 報告或標準化工作簿,IronXL 支持基於模板的生成,允許開發人員從模板創建 Excel 檔案,而無需處理 Open XML SDK、rels 檔案或各種資料夾:

// Load existing template
WorkBook templateBook = WorkBook.Load("ReportTemplate.xlsx");
WorkSheet templateSheet = templateBook.DefaultWorkSheet;
// Find and replace template markers
foreach (var cell in templateSheet["A1:Z100"])
{
    if (cell.Text.Contains("{{CompanyName}}"))
        cell.Value = cell.Text.Replace("{{CompanyName}}", "Acme Corp");
    if (cell.Text.Contains("{{ReportDate}}"))
        cell.Value = cell.Text.Replace("{{ReportDate}}", DateTime.Now.ToString("MMMM yyyy"));
}
// Save as new report
templateBook.SaveAs($"Report_{DateTime.Now:yyyyMMdd}.xlsx");
// Load existing template
WorkBook templateBook = WorkBook.Load("ReportTemplate.xlsx");
WorkSheet templateSheet = templateBook.DefaultWorkSheet;
// Find and replace template markers
foreach (var cell in templateSheet["A1:Z100"])
{
    if (cell.Text.Contains("{{CompanyName}}"))
        cell.Value = cell.Text.Replace("{{CompanyName}}", "Acme Corp");
    if (cell.Text.Contains("{{ReportDate}}"))
        cell.Value = cell.Text.Replace("{{ReportDate}}", DateTime.Now.ToString("MMMM yyyy"));
}
// Save as new report
templateBook.SaveAs($"Report_{DateTime.Now:yyyyMMdd}.xlsx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

這種方法在更新動態內容的同時保持一致的格式,非常適合每月報告或標準化文檔。

如何使用 IronXL 在 C# 中創建 Excel 報告:圖 5 - 報告模板與使用模板創建的 Excel 檔案

最佳實踐和疑難排解

在實施 Excel 報告生成時,請牢記以下提示:

  • 處理大文件的內存使用率:分塊處理數據而不是加載整個數據集(Microsoft 對大 Excel 文件的建議
  • 日期格式問題:使用 DateTime.ToOADate() 生成與 Excel 相容的日期(Excel 日期系統解釋
  • 文件被鎖錯誤:始終妥善處置 Excel 對象,使用 using 語句或新的 MemoryStream 方法。
  • 樣式丟失:某些樣式屬性需要先設置背景顏色

結論

IronXL 將 Excel 報告生成從繁瑣的手動過程轉變為自動化、可靠的工作流程。 憑藉其直觀的 API、跨平台支持和全面的功能集,開發人員可以在幾分鐘而不是幾小時內創建專業的 Excel 報告。 易於數據集成、強大的格式選擇和功能支持的組合使 IronXL 成為任何從事 Excel 報告的 C# 開發人員的重要工具。 For developers who are interested, IronXL offers a free trial and further licensing options for companies and individuals.

立即開始使用 IronXL。
green arrow pointer

常見問題解答

如何在 C# 中創建 Excel 報告?

您可以使用 IronXL 庫在 C# 中創建 Excel 報告,該庫簡化了生成包含格式、公式和數據庫集成功能的 Excel 文件的過程。

使用 IronXL 生成 Excel 報告有什麼好處?

IronXL 提供了一種高效方法來自動生成 Excel 報告,減少了手動工作量並最小化了錯誤。它支持多種功能,例如高級格式、公式計算和與數據庫的無縫集成。

在使用 IronXL 創建 Excel 報告時能夠整合數據庫嗎?

是的,IronXL 允許與數據庫輕鬆集成,使您能夠直接從數據庫中提取數據到 Excel 報告中。

可以使用 IronXL 對 Excel 報告進行自定義格式化嗎?

當然可以。IronXL 支持自定義格式,允許您使用特定的字體、顏色和單元格樣式來設計您的 Excel 報告,以符合專業標準。

IronXL 是否支持 Excel 報告中的公式計算?

是的,IronXL 支持在 Excel 報告中使用公式,從而在生成的 Excel 文件中進行計算和數據分析。

為什麼要在我的 .NET 應用程序中自動化 Excel 報告生成?

在您的 .NET 應用程序中自動化 Excel 報告生成可以節省時間,減少人為錯誤,並通過消除手動報告創建中重複的任務來提高生產力。

在創建 Excel 報告時,IronXL 能處理大數據集嗎?

IronXL 被設計成可以高效處理大數據集,這使其非常適合生成需要處理大量數據的 Excel 報告。

使用 IronXL 可以創建哪些類型的 Excel 報告?

使用 IronXL,您可以根據您的特定業務需求創建各種類型的 Excel 報告,如財務報表、銷售分析、庫存儀表板等。

IronXL 如何幫助減少 Excel 報告創建中的手動工作量?

IronXL 通過以編程方式生成 Excel 文件來自動化報告創建過程,這大大減少了涉及格式化、數據輸入和計算的手動工作。

IronXL 適合創建專業的 Excel 報告嗎?

是的,IronXL 適合創建專業的 Excel 報告,提供多種功能,確保您的報告格式良好、準確,並可立即用於商業用途。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。