跳過到頁腳內容
使用 IRONXL

如何使用 IronXL 在 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
Install-Package IronXL.Excel
SHELL

如何使用 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");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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,您無需 Microsoft Office 即可在 C# 中將資料匯出到現有的 Excel 範本。 IronXL 讓您在填充動態資料的同時,保留 Excel 範本的格式、公式和佈局。

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

IronXL 提供了一種高效能的解決方案,可保留範本格式並提供高級功能,例如從各種來源(如資料集物件)插入數據,而無需依賴 Excel Interop 或 Microsoft Office。

使用 IronXL 是否必須安裝 Microsoft Office?

不,IronXL 不需要安裝 Microsoft Office。它可以獨立運行,使您能夠處理 Excel 文件和模板,而無需依賴任何 Office 軟體。

IronXL 能夠處理帶有公式的複雜 Excel 模板嗎?

是的,IronXL 可以處理複雜的 Excel 模板,包括帶有公式的模板,確保在匯出資料時保留所有現有功能和佈局。

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

IronXL 可以從各種來源匯出數據,包括資料集對象,從而可以靈活地使用所需的資料填充 Excel 範本。

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

IronXL 允許將資料無縫匯出到現有的 Excel 模板,而無需依賴 Office,從而簡化了報表產生過程,節省了時間和資源。

IronXL 是否適合產生專業的 Excel 表格輸出?

是的,IronXL 旨在透過保持模板的完整性並確保高品質的資料整合來創建專業的 Excel 表格輸出。

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