跳過到頁腳內容
使用 IRONXL

如何使用 IronXL.Excel 在 C# 中將 Excel 資料匯出至現有的 Excel 檔案範本

使用 Microsoft Excel 範本可以簡化報表產生流程,因為它能夠保留格式、公式和佈局,同時動態填入資料。 本教學課程示範如何使用 IronXL 將資料高效匯出至現有的 Excel 工作表模板,而無需依賴 Microsoft Office 或 Excel Interop。以下範例展示如何將資料寫入 Excel 範本並建立專業的 Excel 表格輸出。 假設您正在尋找一種方法,在沒有安裝 Microsoft Office 的情況下,將檔案匯出到已存在的 Excel 範本。 在這種情況下,該 Excel 庫提供了一個簡潔、高效能的解決方案,具有更高級的功能,可讓您從各種來源(包括資料集物件)插入資料。

除了 Excel 工作簿之外,IronXL 還與其他資料交換格式(如 XML 檔案)很好地集成,使開發人員能夠輕鬆地在系統之間匯入、匯出或轉換結構化資料。 無論您需要將資料庫或系統檔案中的資料寫入 Excel,此程式庫都支援與 .NET 應用程式無縫整合。

如何使用 IronXL 在 C# 中將 Excel 資料匯出到現有的 Excel 檔案範本:圖 1 - IronXL

為什麼要使用Excel模板進行資料匯出?

與從頭開始建立電子表格相比,Excel 範本具有顯著優勢。 範本可以保持專業的格式、複雜的公式、條件格式規則和經過驗證的資料結構。 組織通常有標準化的發票、報告和儀表板模板,這些模板必須在保留其設計的同時,整合來自資料庫、API 或資料表等集合物件的動態資料。 對輸出檔案套用條件格式和儲存格格式時,範本可確保所有產生的 XLSX 格式文件保持一致。

透過以程式設計方式填入現有模板,開發人員可以節省無數的格式化工作時間,並確保所有產生的文件的一致性。 IronXL 讓這一過程變得無縫,支援各種 Excel 格式,包括 XLSX、XLS 檔案、XLSM 和 XLTX 模板,而無需安裝 Office。 這些操作的原始程式碼簡單明了,易於在任何專案資料夾中實現。

如何使用 IronXL 在 C# 中將 Excel 資料匯出到現有的 Excel 檔案範本:圖 2 - 跨平台

設定 IronXL 以進行模板操作

首先透過 NuGet 套件管理器安裝 IronXL。 開啟軟體包管理器控制台並執行以下命令:

Install-Package IronXL.Excel

如何使用 IronXL 在 C# 中將 Excel 資料匯出到現有的 Excel 檔案範本:圖 3 - 安裝

安裝完成後,將必要的命名空間新增至您的 C# 檔案:

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

IronXL 無需安裝 Microsoft Office 即可獨立運行,因此非常適合伺服器環境和跨平台應用程序,包括 Docker 容器和雲端平台。 有關詳細的設定說明和更多信息,請訪問IronXL 入門指南。 該程式庫支援 Windows、Linux 和 macOS 環境下的 .NET Framework、.NET Core 和 .NET 5+,使其成為 .NET 應用程式的理想選擇。

如何使用 IronXL 在 C# 中將 Excel 資料匯出到現有 Excel 檔案範本:圖 4 - 功能

載入和填充 Excel 模板

使用 IronXL 的WorkBook.Load()方法載入現有模板非常簡單。 以下範例展示如何開啟範本並填充數據,將第一行作為標題,並有效地管理列名:

// Load the existing Excel template for data import
WorkBook workbook = WorkBook.Load("ReportTemplate.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;
// Populate specific worksheet cells with data
sheet["B2"].Value = "Q4 2024 Sales Report";
sheet["C4"].StringValue = DateTime.Now.ToString("MMMM dd, yyyy");
sheet["C6"].DecimalValue = 125000.50m;
sheet["C7"].DecimalValue = 98500.75m;
sheet["C8"].Formula = "=C6-C7"; // Profit calculation
// Populate a range with array 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 template
workbook.SaveAs("Q4_Sales_Report.xlsx");
// Load the existing Excel template for data import
WorkBook workbook = WorkBook.Load("ReportTemplate.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;
// Populate specific worksheet cells with data
sheet["B2"].Value = "Q4 2024 Sales Report";
sheet["C4"].StringValue = DateTime.Now.ToString("MMMM dd, yyyy");
sheet["C6"].DecimalValue = 125000.50m;
sheet["C7"].DecimalValue = 98500.75m;
sheet["C8"].Formula = "=C6-C7"; // Profit calculation
// Populate a range with array 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 template
workbook.SaveAs("Q4_Sales_Report.xlsx");
Imports System

' Load the existing Excel template for data import
Dim workbook As WorkBook = WorkBook.Load("ReportTemplate.xlsx")
Dim sheet As WorkSheet = workbook.DefaultWorkSheet
' Populate specific worksheet cells with data
sheet("B2").Value = "Q4 2024 Sales Report"
sheet("C4").StringValue = DateTime.Now.ToString("MMMM dd, yyyy")
sheet("C6").DecimalValue = 125000.50D
sheet("C7").DecimalValue = 98500.75D
sheet("C8").Formula = "=C6-C7" ' Profit calculation
' Populate a range with array 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 template
workbook.SaveAs("Q4_Sales_Report.xlsx")
$vbLabelText   $csharpLabel

這段程式碼載入一個預先設計的模板,保留所有現有格式,並用新資料填入特定儲存格。 DecimalValue屬性確保數值資料保持正確的格式。 當相鄰資料發生變化時,公式單元格會自動重新計算,從而保持模板的計算邏輯。 了解更多關於在 IronXL 中使用 Excel 公式的資訊。

輸入

如何使用 IronXL 在 C# 中將 Excel 資料匯出到現有的 Excel 檔案範本:圖 5 - 範例範本輸入

輸出

如何使用 IronXL 在 C# 中將 Excel 資料匯出到現有的 Excel 檔案範本:圖 6 - 載入 Excel 範本輸出

使用模板佔位符

許多範本使用佔位符文字標記,需要替換為實際資料。 IronXL 透過儲存格迭代和文字替換有效地處理這種情況。 當您需要將資料寫入 Excel 範本並插入動態內容時,此方法可提供最大的靈活性:

// Load template with placeholders
WorkBook workbook = WorkBook.Load("InvoiceTemplate.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;
// Find and replace placeholder text in cells
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-2024-001");
}
// Populate line items dynamically
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");
// Load template with placeholders
WorkBook workbook = WorkBook.Load("InvoiceTemplate.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;
// Find and replace placeholder text in cells
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-2024-001");
}
// Populate line items dynamically
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 System

' Load template with placeholders
Dim workbook As WorkBook = WorkBook.Load("InvoiceTemplate.xlsx")
Dim sheet As WorkSheet = workbook.DefaultWorkSheet
' Find and replace placeholder text in cells
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-2024-001")
    End If
Next
' Populate line items dynamically
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 的儲存格樣式選項,以便在需要時動態修改格式。

實際應用範例

以下是一個完整的範例,示範如何使用具有預先格式化儲存格的現有 Excel 範本產生每月銷售報告。 此程式碼示範如何處理物件發送者事件並編寫綜合報告。 當處理來自系統資料庫或記憶體集合的資料時,可以使用新的 DataTable 或現有 DataSet 來填入模板,從而有效率地將資料匯出到 Excel:

public void GenerateMonthlyReport(string templatePath, Dictionary<string, decimal> salesData)
{
    // Load the existing template file
    WorkBook workbook = WorkBook.Load(templatePath);
    WorkSheet sheet = workbook.GetWorkSheet("Monthly Report");
    // Set report header information
    sheet["B2"].Value = $"Sales Report - {DateTime.Now:MMMM yyyy}";
    sheet["B3"].Value = $"Generated: {DateTime.Now:g}";
    // Populate sales data starting from row 6
    int currentRow = 6;
    decimal totalSales = 0;
    foreach (var sale in salesData)
    {
        sheet[$"B{currentRow}"].Value = sale.Key;  // Product name
        sheet[$"C{currentRow}"].DecimalValue = sale.Value;  // Sales amount
        sheet[$"D{currentRow}"].Formula = $"=C{currentRow}/C${salesData.Count + 6}*100"; // Percentage formula
        totalSales += sale.Value;
        currentRow++;
    }
    // Update total row with sum
    sheet[$"C{currentRow}"].DecimalValue = totalSales;
    sheet[$"C{currentRow}"].Style.Font.Bold = true;
    // Save with timestamp
    string outputPath = $"Reports/Monthly_Report_{DateTime.Now:yyyyMMdd}.xlsx";
    workbook.SaveAs(outputPath);
}
public void GenerateMonthlyReport(string templatePath, Dictionary<string, decimal> salesData)
{
    // Load the existing template file
    WorkBook workbook = WorkBook.Load(templatePath);
    WorkSheet sheet = workbook.GetWorkSheet("Monthly Report");
    // Set report header information
    sheet["B2"].Value = $"Sales Report - {DateTime.Now:MMMM yyyy}";
    sheet["B3"].Value = $"Generated: {DateTime.Now:g}";
    // Populate sales data starting from row 6
    int currentRow = 6;
    decimal totalSales = 0;
    foreach (var sale in salesData)
    {
        sheet[$"B{currentRow}"].Value = sale.Key;  // Product name
        sheet[$"C{currentRow}"].DecimalValue = sale.Value;  // Sales amount
        sheet[$"D{currentRow}"].Formula = $"=C{currentRow}/C${salesData.Count + 6}*100"; // Percentage formula
        totalSales += sale.Value;
        currentRow++;
    }
    // Update total row with sum
    sheet[$"C{currentRow}"].DecimalValue = totalSales;
    sheet[$"C{currentRow}"].Style.Font.Bold = true;
    // Save with timestamp
    string outputPath = $"Reports/Monthly_Report_{DateTime.Now:yyyyMMdd}.xlsx";
    workbook.SaveAs(outputPath);
}
Public Sub GenerateMonthlyReport(templatePath As String, salesData As Dictionary(Of String, Decimal))
    ' Load the existing template file
    Dim workbook As WorkBook = WorkBook.Load(templatePath)
    Dim sheet As WorkSheet = workbook.GetWorkSheet("Monthly Report")
    ' Set report header information
    sheet("B2").Value = $"Sales Report - {DateTime.Now:MMMM yyyy}"
    sheet("B3").Value = $"Generated: {DateTime.Now:g}"
    ' Populate sales data starting from row 6
    Dim currentRow As Integer = 6
    Dim totalSales As Decimal = 0
    For Each sale In salesData
        sheet($"B{currentRow}").Value = sale.Key ' Product name
        sheet($"C{currentRow}").DecimalValue = sale.Value ' Sales amount
        sheet($"D{currentRow}").Formula = $"=C{currentRow}/C${salesData.Count + 6}*100" ' Percentage formula
        totalSales += sale.Value
        currentRow += 1
    Next
    ' Update total row with sum
    sheet($"C{currentRow}").DecimalValue = totalSales
    sheet($"C{currentRow}").Style.Font.Bold = True
    ' Save with timestamp
    Dim outputPath As String = $"Reports/Monthly_Report_{DateTime.Now:yyyyMMdd}.xlsx"
    workbook.SaveAs(outputPath)
End Sub
$vbLabelText   $csharpLabel

此方法接受銷售數據並填入標準化模板,自動計算百分比和總計,同時保持模板的專業外觀。 範本中現有的圖表和條件格式會根據新資料自動更新。 注意:從 DataTable 物件或 DataSet 集合傳送資料至 Excel 時,請保留列名並將第一行作為標題處理。

以下範例方法無論您需要從字典寫入資料、從資料庫查詢插入值,還是從各種系統來源將資料匯出到 Excel,都能無縫運作。 只需將輸出檔案儲存到您指定的資料夾即可輕鬆存取。 有關使用 DataTables 的更多信息,請參閱 DataTable 導入文件和原始碼範例。

輸入

如何使用 IronXL 在 C# 中將 Excel 資料匯出到現有的 Excel 檔案範本:圖 7 - Excel 範本輸入

輸出

如何使用 IronXL 在 C# 中將 Excel 資料匯出到現有的 Excel 檔案範本:圖 8 - 月度報告輸出

疑難排解常見問題

使用範本時,請確保檔案路徑正確,且範本沒有被其他進程鎖定。 對於受密碼保護的模板,請使用WorkBook.Load(&quot;template.xlsx&quot;, &quot;password&quot;) 。 如果公式沒有更新,請在填入資料後呼叫sheet.Calculate() 。 對於大型資料集,請考慮使用具有串流選項的workbook.SaveAs()來最佳化記憶體使用。 在不同的系統環境下處理 xlsx 格式檔案時,請查閱故障排除文件以取得更多資訊和解決方案。

結論

IronXL 簡化了 C# 中的 Excel 範本填充,在保持複雜格式的同時,還能有效率地從各種來源(包括資料集物件和資料庫連接)注入動態資料。 這種方法可以顯著縮短開發時間,並保持組織內所有報告工作流程的文件一致性。 無論您需要將資料寫入 Excel、插入新行,還是對輸出檔案套用儲存格格式,IronXL 都提供了在 .NET 應用程式中實現專業 Excel 自動化所需的工具。

準備好簡化您的 Excel 報表製作流程了嗎? 立即開始免費試用 IronXL,測試範本填入您的專案中,或探索更多 Excel 自動化教學以增強您的工作流程。 若要進行生產部署,請檢視 適合您需求的授權選項

如何使用 IronXL 在 C# 中將 Excel 資料匯出到現有的 Excel 檔案範本:圖 9 - 許可

常見問題解答

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

使用 IronXL,您可以用 C# 將資料匯出到現有的 Excel 模版,而不需要 Microsoft Office。IronXL.Excel 可讓您保持 Excel 範本的格式、公式和佈局,同時以動態資料填充。

使用 IronXL.Excel 匯出範本有哪些好處?

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

使用 IronXL 是否需要安裝 Microsoft Office?

不,IronXL 不需要安裝 Microsoft Office。它可以獨立運作,讓您可以使用 Excel 檔案和範本,而無需任何 Office 依賴。

IronXL.Excel 可以處理複雜的 Excel 範本公式嗎?

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

IronXL.Excel 可以將哪些類型的資料來源匯出至 Excel 範本?

IronXL.Excel 可以匯出各種來源的資料,包括資料集物件,讓您可以靈活地在 Excel 範本中填入所需的資料。

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

IronXL.Excel 允許將資料無縫匯出至現有的 Excel 範本,而不需要依賴 Office,因此可以簡化報表的產生流程,節省時間與資源。

IronXL 是否適合建立專業的 Excel 表單輸出?

是的,IronXL.Excel 旨在透過維持範本的完整性,並確保高品質的資料整合,來建立專業的 Excel 表單輸出。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。