跳至頁尾內容
使用 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 可讓您將資料匯出到現有的 Excel 模板,而無需 Microsoft Office 或 Excel Interop,從而有效地保留格式、公式和佈局。

我可以使用 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 的高效能解決方案。

是否可以使用 C# 在不依賴外部程式庫的情況下將資料匯出到 Excel 工作表範本?

是的,IronXL 允許您使用 C# 將資料匯出到 Excel 工作表模板,而無需依賴 Microsoft Office 等外部依賴項。

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

IronXL 簡化了報表產生過程,讓使用者可以將資料直接匯出到 Excel 範本中,保留原始格式和佈局,無需手動調整。

喬迪·巴迪亞
軟體工程師
喬迪精通Python、C#和C++,除了在Iron Software運用這些技能外,他還從事遊戲程式設計。他參與產品測試、產品開發和研究等工作,為產品的持續改進做出了巨大貢獻。豐富的經驗讓他始終保持挑戰性和工作熱情,他表示這是他最喜歡在Iron Software工作的原因之一。喬迪在佛羅裡達州邁阿密長大,畢業於佛羅裡達大學,主修電腦科學和統計學。