跳過到頁腳內容
使用 IRONXL

如何在 C# 中匯出模板

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

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

如何在 C# 中匯出範本:圖 1

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

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

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

如何在 C# 匯出範本:圖 2

設定 IronXL 以進行模板操作

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

Install-Package IronXL.Excel

如何在 C# 匯出範本:圖 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 應用程式的理想選擇。

如何在 C# 中匯出範本:圖 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 公式的資訊。

輸入

如何在 C# 中匯出範本:圖 5 - 範本輸入範例

輸出

如何在 C# 中匯出範本:圖 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 範本產生每月銷售報告。 此程式碼示範如何處理物件發送者事件並編寫綜合報告。 當處理來自系統資料庫或記憶體集合的資料時,可以使用新的資料表或現有資料集填充模板,從而有效率地將資料匯出到 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 物件或資料集集合傳送資料至 Excel 時,請保留列名並將第一行作為標題。

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

輸入

如何在 C# 中匯出範本:圖 7 - Excel 範本輸入

輸出

如何在 C# 中匯出範本:圖 8 - 月度報告輸出

疑難排解常見問題

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

結論

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

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

如何在 C# 匯出範本:圖 9 - 許可

常見問題解答

使用 IronXL 將資料匯出至 Excel 範本的優點為何?

IronXL.Excel 可讓您將資料匯出至現有的 Excel 範本,而不需要 Microsoft Office 或 Excel Interop,並可有效地保留格式、公式和版面設計。

我可以使用 IronXL 將資料集物件的資料匯出至 Excel 範本嗎?

是的,IronXL.Excel 支援將資料從各種來源(包括資料集物件)匯出至 Excel 範本,同時維持現有的範本結構。

使用 IronXL.Excel 操作是否需要 Microsoft Office?

不會,IronXL.Excel 獨立於 Microsoft Office 運作,提供簡潔且高效能的解決方案,以 C# 語言處理 Excel 範本。

IronXL.Excel 在匯出資料至 Excel 範本時如何處理格式化?

IronXL.Excel 會保留您 Excel 範本的現有格式、公式和排版,確保您的資料能無縫匯出為所需的結構。

IronXL.Excel 可以創建哪種 Excel 輸出?

IronXL.Excel 可以將資料寫入範本,並保持原始格式和結構的完整性,從而建立專業的 Excel 表單輸出。

IronXL 是否支援 Excel 範本中的動態資料填充?

是的,IronXL.Excel 支援動態資料填充,可讓您有效率地在 Excel 範本中填充來自不同來源的資料,同時維持範本的完整性。

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

IronXL.Excel 能夠處理包含公式的複雜 Excel 範本,確保資料匯出後公式保持完整且功能正常。

是什麼讓 IronXL 成為匯出資料至 Excel 的高效能解決方案?

IronXL.Excel 獨立於 Microsoft Office 的工作能力及其處理各種資料來源的先進功能,使其成為匯出資料至 Excel 的高效能解決方案。

是否可以使用 C# 將資料匯出至 Excel 工作表範本,而不需要外部依賴?

是的,IronXL.Excel 允許您使用 C# 將資料匯出至 Excel 工作表範本,而無需依賴 Microsoft Office 等外部依賴。

IronXL.Excel 如何簡化在 Excel 中產生報表的過程?

IronXL.Excel 可讓使用者直接將資料匯出至 Excel 範本,保留原始格式與版面,省去手動調整的麻煩,進而簡化報表的產生。

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