跳至頁尾內容
USING IRONXL

如何使用 IronXL 在 C# 中將資料匯出到現有的 Excel 模板

使用Microsoft Excel範本讓您在動態填充資料的同時保存格式、公式和佈局。 本教程演示如何使用IronXL將資料導出至現有Excel工作表範本,而不需要Microsoft Office依賴或Excel Interop。您將學習如何載入預設範本、替換佔位符標記、寫入表格資料、處理常見邊緣情況,並在任何.NET 10應用程式中保存專業的XLSX輸出。

如果您需要在未安裝Microsoft Office的情況下導出至已存在的Excel範本,IronXL提供了一個高性能解決方案,支持從字典、列表、DataTable物件和資料庫查詢結果中插入資料。 無論您的範本是格式化的發票、月度儀表板,還是合規報告,IronXL都能以程式方式填充它們並在過程中保存每一個樣式規則、公式和條件格式。

如何使用IronXL在C#中將Excel資料導出至現有Excel文件範本:圖片1 - IronXL

為什麼Excel範本改善了報告生成?

Excel範本相較於從頭構建電子表格提供了顯著的優勢。 範本維持專業的格式、複雜的公式、條件格式規則和已被您的組織批准的驗證資料結構。 財務團隊、運營部門和合規小組通常會有針對發票、儀表板和監管申報的標準化範本,它們必須保留設計,同時整合來自資料庫、API或記憶體集合的新資料。

通過程式化填充現有範本,您節省了數小時的格式工作,並保證每個生成的文件的一致性。 IronXL支持XLSX、XLS、XLSM和XLTX格式,無需安裝Office,因此適用於伺服器環境、Docker容器和雲端管道,安裝Microsoft Office是不切實際或不可能的。

範本方法的主要好處:

  • 公式保存 -- 現有的SUM、AVERAGE和查找公式在寫入資料後自動重新計算
  • 樣式保留 -- 字體、邊框、單元格顏色和數字格式完全保持設計
  • 條件格式 -- 與單元格範圍綁定的規則繼續根據新資料值觸發
  • 零Office依賴 -- IronXL完全在託管.NET程式碼中讀寫Excel文件
  • 跨平台支持 -- 運行於Windows、Linux和macOS,包括.NET 10環境

如何使用IronXL在C#中將Excel資料導出至現有Excel文件範本:圖片2 - 多平台

如何在您的項目中安裝IronXL?

開始時通過NuGet安裝IronXL。 打開Package Manager Console並運行:

Install-Package IronXL.Excel

或者使用.NET CLI:

dotnet add package IronXL.Excel

如何使用IronXL在C#中將Excel資料導出至現有Excel文件範本:圖片3 - 安裝

IronXL獨立運作,不需要Microsoft Office安裝,這使得它成為伺服器環境和跨平台應用程式的理想選擇。 有關詳細的設置指導,請存取IronXL入門指南。 該程式庫目標於.NET Framework、.NET Core和.NET 5至.NET 10,運行於Windows、Linux和macOS。

安裝後,在文件頂部新增命名空間:

using IronXL;
using IronXL;
Imports IronXL
$vbLabelText   $csharpLabel

如何使用IronXL在C#中將Excel資料導出至現有Excel文件範本:圖片4 - 特點

如何載入和填充現有的Excel範本?

使用IronXL的WorkBook.Load()方法載入現有的範本非常簡單。 下面的範例打開一個季度銷售報告範本,使用頂級語句用資料填充特定的單元格:

using IronXL;

// Load the existing Excel template
WorkBook workbook = WorkBook.Load("ReportTemplate.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;

// Write header values to named cells
sheet["B2"].Value = "Q4 2025 Sales Report";
sheet["C4"].StringValue = DateTime.Now.ToString("MMMM dd, yyyy");
sheet["C6"].DecimalValue = 125000.50m;
sheet["C7"].DecimalValue = 98500.75m;

// Add a profit formula -- Excel recalculates automatically
sheet["C8"].Formula = "=C6-C7";

// Populate a column range with monthly data
decimal[] monthlyData = { 10500, 12300, 15600, 11200 };
for (int i = 0; i < monthlyData.Length; i++)
{
    sheet[$"E{10 + i}"].DecimalValue = monthlyData[i];
}

// Save the populated file
workbook.SaveAs("Q4_Sales_Report.xlsx");
using IronXL;

// Load the existing Excel template
WorkBook workbook = WorkBook.Load("ReportTemplate.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;

// Write header values to named cells
sheet["B2"].Value = "Q4 2025 Sales Report";
sheet["C4"].StringValue = DateTime.Now.ToString("MMMM dd, yyyy");
sheet["C6"].DecimalValue = 125000.50m;
sheet["C7"].DecimalValue = 98500.75m;

// Add a profit formula -- Excel recalculates automatically
sheet["C8"].Formula = "=C6-C7";

// Populate a column range with monthly data
decimal[] monthlyData = { 10500, 12300, 15600, 11200 };
for (int i = 0; i < monthlyData.Length; i++)
{
    sheet[$"E{10 + i}"].DecimalValue = monthlyData[i];
}

// Save the populated file
workbook.SaveAs("Q4_Sales_Report.xlsx");
Imports IronXL

' Load the existing Excel template
Dim workbook As WorkBook = WorkBook.Load("ReportTemplate.xlsx")
Dim sheet As WorkSheet = workbook.DefaultWorkSheet

' Write header values to named cells
sheet("B2").Value = "Q4 2025 Sales Report"
sheet("C4").StringValue = DateTime.Now.ToString("MMMM dd, yyyy")
sheet("C6").DecimalValue = 125000.50D
sheet("C7").DecimalValue = 98500.75D

' Add a profit formula -- Excel recalculates automatically
sheet("C8").Formula = "=C6-C7"

' Populate a column range with monthly data
Dim monthlyData As Decimal() = {10500D, 12300D, 15600D, 11200D}
For i As Integer = 0 To monthlyData.Length - 1
    sheet($"E{10 + i}").DecimalValue = monthlyData(i)
Next

' Save the populated file
workbook.SaveAs("Q4_Sales_Report.xlsx")
$vbLabelText   $csharpLabel

此程式碼載入預設範本,保存所有現有格式,並填充特定單元格。 DecimalValue屬性確保數字資料保留正確的貨幣或小數格式。 公式單元格在相鄰資料變更時自動重新計算,因此範本的計算邏輯保持完整。

如需關於使用Excel單元格參考和範圍的指導,請參見IronXL單元格和範圍文件。 您還可以使用IronXL例子頁面探討更多模式。

輸入

如何使用IronXL在C#中將Excel資料導出至現有Excel文件範本:圖片5 - 範例範本輸入

輸出

如何使用IronXL在C#中將Excel資料導出至現有Excel文件範本:圖片6 - 載入Excel範本輸出

如何在範本中替換佔位符標記?

許多範本使用佔位符文字標記 -- 例如,{{InvoiceDate}} -- 這需要用實際執行時值替換。 IronXL透過對定義範圍的單元格迭代來處理這一點。 此模式特別適合發票生成、合同填充和個性化報告建立:

using IronXL;

// Load an invoice template containing placeholder markers
WorkBook workbook = WorkBook.Load("InvoiceTemplate.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;

// Iterate over a range and replace placeholder text
foreach (var cell in sheet["A1:H50"])
{
    if (cell.Text.Contains("{{CustomerName}}"))
        cell.Value = cell.Text.Replace("{{CustomerName}}", "Acme Corporation");

    if (cell.Text.Contains("{{InvoiceDate}}"))
        cell.Value = cell.Text.Replace("{{InvoiceDate}}", DateTime.Now.ToShortDateString());

    if (cell.Text.Contains("{{InvoiceNumber}}"))
        cell.Value = cell.Text.Replace("{{InvoiceNumber}}", "INV-2025-001");
}

// Append line items starting at row 15
var items = new[]
{
    new { Description = "Software License", Qty = 5, Price = 299.99 },
    new { Description = "Support Package",  Qty = 1, Price = 999.99 }
};

int startRow = 15;
foreach (var item in items)
{
    sheet[$"B{startRow}"].Value      = item.Description;
    sheet[$"E{startRow}"].IntValue   = item.Qty;
    sheet[$"F{startRow}"].DoubleValue = item.Price;
    sheet[$"G{startRow}"].Formula    = $"=E{startRow}*F{startRow}";
    startRow++;
}

workbook.SaveAs("GeneratedInvoice.xlsx");
using IronXL;

// Load an invoice template containing placeholder markers
WorkBook workbook = WorkBook.Load("InvoiceTemplate.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;

// Iterate over a range and replace placeholder text
foreach (var cell in sheet["A1:H50"])
{
    if (cell.Text.Contains("{{CustomerName}}"))
        cell.Value = cell.Text.Replace("{{CustomerName}}", "Acme Corporation");

    if (cell.Text.Contains("{{InvoiceDate}}"))
        cell.Value = cell.Text.Replace("{{InvoiceDate}}", DateTime.Now.ToShortDateString());

    if (cell.Text.Contains("{{InvoiceNumber}}"))
        cell.Value = cell.Text.Replace("{{InvoiceNumber}}", "INV-2025-001");
}

// Append line items starting at row 15
var items = new[]
{
    new { Description = "Software License", Qty = 5, Price = 299.99 },
    new { Description = "Support Package",  Qty = 1, Price = 999.99 }
};

int startRow = 15;
foreach (var item in items)
{
    sheet[$"B{startRow}"].Value      = item.Description;
    sheet[$"E{startRow}"].IntValue   = item.Qty;
    sheet[$"F{startRow}"].DoubleValue = item.Price;
    sheet[$"G{startRow}"].Formula    = $"=E{startRow}*F{startRow}";
    startRow++;
}

workbook.SaveAs("GeneratedInvoice.xlsx");
Imports IronXL

' Load an invoice template containing placeholder markers
Dim workbook As WorkBook = WorkBook.Load("InvoiceTemplate.xlsx")
Dim sheet As WorkSheet = workbook.DefaultWorkSheet

' Iterate over a range and replace placeholder text
For Each cell In sheet("A1:H50")
    If cell.Text.Contains("{{CustomerName}}") Then
        cell.Value = cell.Text.Replace("{{CustomerName}}", "Acme Corporation")
    End If

    If cell.Text.Contains("{{InvoiceDate}}") Then
        cell.Value = cell.Text.Replace("{{InvoiceDate}}", DateTime.Now.ToShortDateString())
    End If

    If cell.Text.Contains("{{InvoiceNumber}}") Then
        cell.Value = cell.Text.Replace("{{InvoiceNumber}}", "INV-2025-001")
    End If
Next

' Append line items starting at row 15
Dim items = {
    New With {.Description = "Software License", .Qty = 5, .Price = 299.99},
    New With {.Description = "Support Package", .Qty = 1, .Price = 999.99}
}

Dim startRow As Integer = 15
For Each item In items
    sheet($"B{startRow}").Value = item.Description
    sheet($"E{startRow}").IntValue = item.Qty
    sheet($"F{startRow}").DoubleValue = item.Price
    sheet($"G{startRow}").Formula = $"=E{startRow}*F{startRow}"
    startRow += 1
Next

workbook.SaveAs("GeneratedInvoice.xlsx")
$vbLabelText   $csharpLabel

此方法在定義的單元格範圍內搜尋標記,並將其替換為實際值。 範本的格式 -- 字體、顏色、邊框和數字格式 -- 在整個過程中保持不變。 更多關於執行時進行高級樣式更改的資訊,請參見IronXL單元格樣式指南,其中涵蓋背景顏色、字體屬性和邊框樣式。

如何選擇正確的單元格範圍以進行迭代?

在迭代以尋找佔位符時,選擇一個涵蓋所有包含標記的單元格而不會不必要過大的範圍。 像"A1:H50"這樣的範圍對於大多數發票範本來說是有效的。 對於資料分佈在數百行的範本,限製迭代至頁首區域,並使用直接單元格尋址來填充資料正文。 這能夠使性能在大型工作簿上保持可預測。

如何處理缺失或不匹配的佔位符?

在調用.Replace()之前新增空或空值檢查以避免模板版本不同時例外。 您可以記錄未解析的佔位符以進行除錯:

using IronXL;

WorkBook workbook = WorkBook.Load("InvoiceTemplate.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;

var replacements = new Dictionary<string, string>
{
    { "{{CustomerName}}", "Acme Corporation" },
    { "{{InvoiceDate}}", DateTime.Now.ToShortDateString() },
    { "{{InvoiceNumber}}", "INV-2025-002" }
};

foreach (var cell in sheet["A1:H50"])
{
    if (string.IsNullOrEmpty(cell.Text)) continue;

    foreach (var replacement in replacements)
    {
        if (cell.Text.Contains(replacement.Key))
            cell.Value = cell.Text.Replace(replacement.Key, replacement.Value);
    }
}

workbook.SaveAs("GeneratedInvoice_Safe.xlsx");
using IronXL;

WorkBook workbook = WorkBook.Load("InvoiceTemplate.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;

var replacements = new Dictionary<string, string>
{
    { "{{CustomerName}}", "Acme Corporation" },
    { "{{InvoiceDate}}", DateTime.Now.ToShortDateString() },
    { "{{InvoiceNumber}}", "INV-2025-002" }
};

foreach (var cell in sheet["A1:H50"])
{
    if (string.IsNullOrEmpty(cell.Text)) continue;

    foreach (var replacement in replacements)
    {
        if (cell.Text.Contains(replacement.Key))
            cell.Value = cell.Text.Replace(replacement.Key, replacement.Value);
    }
}

workbook.SaveAs("GeneratedInvoice_Safe.xlsx");
Imports IronXL

Dim workbook As WorkBook = WorkBook.Load("InvoiceTemplate.xlsx")
Dim sheet As WorkSheet = workbook.DefaultWorkSheet

Dim replacements As New Dictionary(Of String, String) From {
    {"{{CustomerName}}", "Acme Corporation"},
    {"{{InvoiceDate}}", DateTime.Now.ToShortDateString()},
    {"{{InvoiceNumber}}", "INV-2025-002"}
}

For Each cell In sheet("A1:H50")
    If String.IsNullOrEmpty(cell.Text) Then Continue For

    For Each replacement In replacements
        If cell.Text.Contains(replacement.Key) Then
            cell.Value = cell.Text.Replace(replacement.Key, replacement.Value)
        End If
    Next
Next

workbook.SaveAs("GeneratedInvoice_Safe.xlsx")
$vbLabelText   $csharpLabel

使用替換字典使得程式碼在新增新佔位符型別至模版時更易於維護和擴展。

如何從模板生成月度報告?

以下是一個真實範例,從包含預設格式單元格、圖表和百分比公式的現有Excel模板中生成月度銷售報告。 此程式碼使用頂級語句,並接受產品與銷售對應關係的字典:

using IronXL;

// Load the monthly report template
WorkBook workbook = WorkBook.Load("MonthlyReportTemplate.xlsx");
WorkSheet sheet = workbook.GetWorkSheet("Monthly Report");

// Build sample sales data
var salesData = new Dictionary<string, decimal>
{
    { "Product A", 42500.00m },
    { "Product B", 31750.50m },
    { "Product C", 18300.25m }
};

// Write report header
sheet["B2"].Value = $"Sales Report - {DateTime.Now:MMMM yyyy}";
sheet["B3"].Value = $"Generated: {DateTime.Now:g}";

// Write each product row starting at row 6
int currentRow = 6;
decimal totalSales = salesData.Values.Sum();

foreach (var sale in salesData)
{
    sheet[$"B{currentRow}"].Value = sale.Key;
    sheet[$"C{currentRow}"].DecimalValue = sale.Value;
    // Percentage of total formula
    sheet[$"D{currentRow}"].Formula = $"=C{currentRow}/C{currentRow + salesData.Count}*100";
    currentRow++;
}

// Write the total row and apply bold style
sheet[$"C{currentRow}"].DecimalValue = totalSales;
sheet[$"C{currentRow}"].Style.Font.Bold = true;

// Save with a date-stamped filename
string outputPath = $"Reports/Monthly_Report_{DateTime.Now:yyyyMMdd}.xlsx";
workbook.SaveAs(outputPath);
using IronXL;

// Load the monthly report template
WorkBook workbook = WorkBook.Load("MonthlyReportTemplate.xlsx");
WorkSheet sheet = workbook.GetWorkSheet("Monthly Report");

// Build sample sales data
var salesData = new Dictionary<string, decimal>
{
    { "Product A", 42500.00m },
    { "Product B", 31750.50m },
    { "Product C", 18300.25m }
};

// Write report header
sheet["B2"].Value = $"Sales Report - {DateTime.Now:MMMM yyyy}";
sheet["B3"].Value = $"Generated: {DateTime.Now:g}";

// Write each product row starting at row 6
int currentRow = 6;
decimal totalSales = salesData.Values.Sum();

foreach (var sale in salesData)
{
    sheet[$"B{currentRow}"].Value = sale.Key;
    sheet[$"C{currentRow}"].DecimalValue = sale.Value;
    // Percentage of total formula
    sheet[$"D{currentRow}"].Formula = $"=C{currentRow}/C{currentRow + salesData.Count}*100";
    currentRow++;
}

// Write the total row and apply bold style
sheet[$"C{currentRow}"].DecimalValue = totalSales;
sheet[$"C{currentRow}"].Style.Font.Bold = true;

// Save with a date-stamped filename
string outputPath = $"Reports/Monthly_Report_{DateTime.Now:yyyyMMdd}.xlsx";
workbook.SaveAs(outputPath);
Imports IronXL

' Load the monthly report template
Dim workbook As WorkBook = WorkBook.Load("MonthlyReportTemplate.xlsx")
Dim sheet As WorkSheet = workbook.GetWorkSheet("Monthly Report")

' Build sample sales data
Dim salesData As New Dictionary(Of String, Decimal) From {
    {"Product A", 42500.0D},
    {"Product B", 31750.5D},
    {"Product C", 18300.25D}
}

' Write report header
sheet("B2").Value = $"Sales Report - {DateTime.Now:MMMM yyyy}"
sheet("B3").Value = $"Generated: {DateTime.Now:g}"

' Write each product row starting at row 6
Dim currentRow As Integer = 6
Dim totalSales As Decimal = salesData.Values.Sum()

For Each sale In salesData
    sheet($"B{currentRow}").Value = sale.Key
    sheet($"C{currentRow}").DecimalValue = sale.Value
    ' Percentage of total formula
    sheet($"D{currentRow}").Formula = $"=C{currentRow}/C{currentRow + salesData.Count}*100"
    currentRow += 1
Next

' Write the total row and apply bold style
sheet($"C{currentRow}").DecimalValue = totalSales
sheet($"C{currentRow}").Style.Font.Bold = True

' Save with a date-stamped filename
Dim outputPath As String = $"Reports/Monthly_Report_{DateTime.Now:yyyyMMdd}.xlsx"
workbook.SaveAs(outputPath)
$vbLabelText   $csharpLabel

此方法填充標準化範本,自動計算百分比貢獻,並保留範本的專業外觀。 範本中現有的圖表將根據新資料值進行更新,因為其資料源範圍保持不變。

DataSet轉移資料時,保留列名並將第一行視為標題。 有關從DataTable物件導入的更多資訊,請參見IronXL DataTable文件

輸入

如何使用IronXL在C#中將Excel資料導出至現有Excel文件範本:圖片7 - Excel範本輸入

輸出

如何使用IronXL在C#中將Excel資料導出至現有Excel文件範本:圖片8 - 月度報告輸出

如何排除常見的範本錯誤?

在使用範本時,常會定期出現的多個問題。 下表將每個症狀與其原因及解決方案進行了對應:

常見IronXL範本錯誤和解決方案
症狀 可能的原因 解決方案
在載入時出現FileNotFoundException 文件路徑或工作目錄不正確 使用Path.Combine(AppContext.BaseDirectory, "template.xlsx")獲得可靠的路徑
公式顯示過期值 寫入後未觸發自動計算 在保存前調用sheet.Calculate()
密碼保護範本無法打開 範本具有工作簿或工作表密碼 傳遞密碼:WorkBook.Load("template.xlsx", "password")
大資料時記憶體使用量高 在寫入期間整個工作簿保留在記憶體中 使用workbook.SaveAs()進行流式處理,並在保存後釋放工作簿
寫入後丟失單元格格式 直接覆蓋單元格樣式物件 僅設置Value/Formula -- 避免替換整個Style物件
圖表資料未更新 在圖表的源範圍之外寫入 確保資料行保留在命名範圍或提供圖表的表格內

對於密碼保護的文件,提供密碼作為WorkBook.Load的第二個參數。 如果在寫入資料後公式未更新,請先調用workbook.SaveAs()。 對於大型資料集,在保存後釋放工作簿物件以迅速釋放託管和非託管記憶體。

有關更多故障排除資源,請參見IronXL故障排除文件IronXL API 參考

IronXL 支援哪些其他 Excel 操作?

除了範本填充之外,IronXL 提供了廣泛的Excel操作能力,以補充上述工作流程:

這些功能與範本填充一起整合,因此單一工作流程可以載入範本、填充它、保護敏感的公式單元格,並在一次操作中輸出XLSX副本和PDF版本。

IronXL也與其他資料交換格式,如XML整合良好,允許您導入結構化資料,轉換它,然後將結果導出到範本中。 有關與資料庫驅動報告生成的更多高級整合,請參見IronXL部落格上的社群教程。

如何使用IronXL在C#中將Excel資料導出至現有Excel文件範本:圖片9 - 授權

如何在生產環境中開始使用IronXL?

IronXL可免費用於開發和測試。 當您準備好部署時,從涵蓋個別開發者、團隊和OEM再分發的靈活授權選項中選擇。 存取IronXL授權頁面以找到適合您的項目的選項。

為了立即開始,探索免費試用下載並針對您自己的範本運行本教程中的程式碼範例。 IronXL NuGet頁面提供版本歷史和套件詳情。 社群討論和其他範例可在Iron Software GitHub 儲存庫上找到。 關於支撐XLSX文件的Open XML文件格式的背景,請參見ECMA-376規範概覽

對於與替代方案一起評估 IronXL 的組織,IronXL 比較指南涵蓋功能差異、授權模式和性能基準,幫助您做出明智的決定。

常見問題

我如何在 C# 中將資料匯出至現有的 Excel 範本?

using IronXL,您可以在 C# 中將資料匯出至現有的 Excel 範本而無需 Microsoft Office。IronXL 允許您在填充動態資料時保持 Excel 範本的格式、公式和佈局。

using IronXL 匯出 Excel 範本的優勢是什麼?

IronXL 提供了一個高性能的解決方案,保留範本格式並提供先進功能,例如從資料集物件等各種來源插入資料,而不依賴 Excel Interop 或 Microsoft Office。

using IronXL 是否需要安裝 Microsoft Office?

不,IronXL不需要安裝 Microsoft Office。它獨立運行,允許您處理 Excel 文件和範本,無需任何 Office 依賴。

IronXL 能夠處理複雜的含有公式的 Excel 範本嗎?

是的,IronXL 能夠處理複雜的 Excel 範本,包括含有公式的範本,確保所有現有功能和佈局在匯出資料時得以保留。

IronXL 能匯出哪些型別的資料源到 Excel 範本?

IronXL 可以從多種來源(包括資料集物件)匯出資料,提供填充 Excel 範本的靈活性。

IronXL 如何提高工作流程效率?

IronXL 通過允許在無需 Office 依賴的情況下將資料無縫匯出到現有的 Excel 範本,簡化了報告生成過程,節省了時間和資源。

IronXL 適合建立專業的 Excel 表輸出嗎?

是的,IronXL 專為通過保持範本完整性並保證高質量資料整合來建立專業的 Excel 表輸出而設計。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話