如何在 C# 中匯出模板
使用Microsoft Excel範本有助於簡化報表生成,因為它能夠在動態填充資料的同時保留格式化、公式和佈局。 本教程演示如何使用IronXL高效地將資料導出到現有Excel工作表範本中,無需依賴Microsoft Office或Excel Interop。以下範例顯示如何將資料寫入Excel範本並生成專業的Excel工作表輸出。 假設您正在尋找一種方法在沒有安裝Microsoft Office的情況下將C#匯出到已經存在的Excel範本。 在這種情況下,這個Excel程式庫提供了一個乾淨的、高性能的解決方案,具有更高級的功能,允許您從各種來源插入資料,包括資料集物件。
除了Excel工作簿,IronXL還能很好地整合其他資料交換格式,如XML文件,使開發人員能夠輕鬆地在系統之間導入資料、導出或轉換結構化資料。 無論您是需要從資料庫或系統文件中將資料寫入Excel,這個程式庫都支援與.NET應用程式的無縫整合。

為什麼使用Excel範本來導出資料?
使用Excel範本比從頭開始建立電子表格具有顯著的優勢。 範本保持專業格式、複雜的公式、條件格式規則和已驗證的資料結構。 組織通常為發票、報告和儀表板制定標準範本,這些範本必須保留設計,同時結合來自資料庫、API或集合物件(例如資料表)的動態資料。 當將條件格式和單元格格式應用到輸出文件時,範本確保所有生成文件在xlsx格式中保持一致性。
通過程式化地填充現有範本,開發者可以節省無數小時的格式化工作,確保所有生成文件的一致性。 IronXL使此過程能無縫進行,支援各種Excel格式,包括XLSX、XLS文件、XLSM和XLTX範本而無需Office安裝。 這些操作的原始碼簡單易實現,可以在任何專案文件夾中使用。

設置IronXL進行範本操作
首先通過NuGet套件管理器安裝IronXL。 打開您的套件管理器控制台並運行以下命令:
Install-Package IronXL.Excel

安裝後,在您的C#文件中新增必要的命名空間:
using IronXL;
using IronXL;
Imports IronXL
IronXL獨立運行,無需安裝Microsoft Office,非常適合伺服器環境和跨平台應用程式,包括Docker容器和雲平台。 有關詳細的設置指引和更多資訊,請存取IronXL入門指南。 該程式庫支援.NET Framework、.NET Core和.NET 5+,適用於Windows、Linux和macOS環境,是.NET應用程式的理想選擇。

載入和填充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")
此程式碼載入一個預設計的範本,保留所有現有格式,並用新資料填充特定單元格。 DecimalValue屬性確保數值資料保持正確格式。 當鄰近資料發生變化時,公式單元格會自動重新計算,保持範本的計算邏輯不變。 了解有關在IronXL中使用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")
此方法在指定範圍內搜索佔位符標記,並將它們替換為實際值。 範本的格式包括字體、顏色和邊框在整個過程中保持不變。 對於更高級的場景,探索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);
}
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
此方法接受銷售資料並填充標準範本,並在保留範本專業外觀的同時,自動計算百分比和總計。 範本中的現有圖表和條件格式會根據新資料自動更新。 注意:在將DataTable物件或資料集集合的資料轉移到Excel時,保留列名並將第一行作為標題處理。
以下範例方法無論您需要從字典中寫入資料、從資料庫查詢中插入值,還是從各種系統來源中導出資料到Excel時都能無縫運作。 只需將輸出文件儲存到指定的文件夾中即可輕鬆存取。 關於使用DataTables的更多資訊,請參閱DataTable導入文件和程式碼範例。
輸入

輸出

排除常見問題
在使用範本時,確保文件路徑正確並且範本沒有被其他過程鎖定。 對於受密碼保護的範本,請使用WorkBook.Load("template.xlsx", "password")。 如果公式未更新,請在填充資料後調用sheet.Calculate()。 對於大型資料集,請考慮使用具有流選項的workbook.SaveAs()來優化記憶體使用。 檢查疑難排解文件以獲取有關在不同系統環境中使用xlsx格式文件的更多資訊和解決方案。
結論
IronXL簡化了C#中的Excel範本填充,保持複雜格式,並高效注入從各種來源(包括資料集物件和資料庫連接)獲取的動態資料。 此方法顯著減少開發時間,並在您的機構的報告工作流程中維持文件一致性。 無論您需要將資料寫入excel、插入新行或將單元格格式應用到輸出文件,IronXL都提供了.NET應用程式中專業excel自動化所需的工具。
準備好簡化您的Excel報告了嗎? 開始您的免費IronXL試用以在您的專案中測試範本填充,或探索更多Excel自動化教程以增強您的工作流程。 如需生產部署,請查看授權選項以滿足您的需求。

常見問題
使用IronXL將資料匯出至Excel範本有何優勢?
IronXL允許您在不需要Microsoft Office或Excel Interop的情況下將資料匯出至現有的Excel範本,並有效保留格式、公式和佈局。
我可以使用IronXL將資料從dataset物件匯出至Excel範本嗎?
可以,IronXL支持從各種來源(包括dataset物件)將資料匯出至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允許您在不依賴外部依賴如Microsoft Office的情況下使用C#將資料匯出至Excel工作表範本。
IronXL如何簡化Excel報告的生成過程?
IronXL通過允許使用者直接將資料匯出至Excel範本來簡化報告生成,保留原始格式和佈局,消除手動調整的需要。




