跳過到頁腳內容
使用 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;
$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");
$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");
$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);
}
$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允許您在不需要Microsoft Office或Excel Interop的情況下,將數據匯出到現有Excel範本,同時高效保留格式、公式和佈局。

我可以使用IronXL將數據集物件中的數據匯出到Excel範本嗎?

是的,IronXL支持將多種來源的數據匯出到Excel範本,包括數據集物件,同時維持現有的範本結構。

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

不,IronXL獨立於Microsoft Office運行,提供一種乾淨高效的解決方案來處理C#中的Excel範本。

IronXL如何在將數據匯出到Excel範本時處理格式?

IronXL保留了Excel範本的現有格式、公式和佈局,確保數據無縫地輸出到所需的結構中。

IronXL能創建什麼樣的Excel輸出?

IronXL能通過將數據寫入範本並保留原始格式和結構的完整性來創建專業的Excel表格輸出。

IronXL是否支持Excel範本中的動態數據填充?

是的,IronXL 支援動態數據填充,可讓您有效地使用來自不同來源的數據填充 Excel 模板,同時保持模板的完整性。

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

IronXL能夠處理包含公式的複雜Excel範本,確保在數據匯出後公式保持完好和功能正常。

IronXL為什麼是一個匯出數據到Excel的高效解決方案?

IronXL獨立於Microsoft Office運行,並且具有處理各種數據來源的先進功能,使其成為一個匯出數據到Excel的高效解決方案。

是否可以在不依賴外部依賴項(如Microsoft Office)的情況下,使用C#將數據匯出到Excel工作表範本?

是的,IronXL允許您使用C#將數據匯出到Excel工作表範本,而不依賴於外部依賴項如Microsoft Office。

IronXL如何簡化Excel報告生成過程?

IronXL通過允許用戶直接將數據匯出到Excel範本來簡化報告生成,保存原始格式和佈局,並消除手動調整的需要。

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

鋼鐵支援團隊

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