使用 IRONXL 如何在 C# 中使用 IronXL 生成 Excel 文件 Curtis Chau 已发布:十月 19, 2025 Download IronXL NuGet 下载 DLL 下载 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article Generating Excel worksheet files programmatically in C# or Visual Basic traditionally required Microsoft Office installation or complex COM Interop. IronXL changes this completely, offering a simple API that creates Excel application files without any Office dependencies. This tutorial walks you through building Excel files in C# using IronXL, from basic spreadsheet creation to advanced formatting and database integration. Whether you're creating reports, exporting data(XLS file or XLSX files), or automating spreadsheet generation, you'll learn the essential techniques for working with Excel in .NET applications. Why Generate Excel Worksheet Files Without Microsoft Office? Developing Excel generation features without Office dependencies solves critical deployment challenges. Server environments rarely have Microsoft Office installed due to licensing costs and resource overhead. Each Office installation requires significant disk space and memory, making it impractical for cloud deployments or containerized applications. IronXL eliminates these constraints by operating independently. Your C# Excel file generation runs on Windows, Linux, macOS, Docker containers, or Azure App Services without modification. This cross-platform compatibility means you write once and deploy anywhere, whether targeting .NET Framework, .NET Core, or .NET 8/9 applications. Performance improves dramatically without COM Interop overhead. Traditional Office automation creates separate process instances for each operation, consuming memory and CPU resources. IronXL processes everything in-memory within your application's process space, resulting in faster execution and lower resource consumption when you generate Excel files programmatically. Deployment becomes straightforward since IronXL ships as a single NuGet package. Without any registry entries, any COM registration,and any Office service packs to maintain. Your continuous integration pipelines work seamlessly, and Docker containers remain lightweight. This simplified approach has made IronXL a popular choice, as discussed in various developer forums where professionals share their experiences with Excel automation. Some developers still explore Microsoft’s Open XML Productivity Tool for working directly with Office Open XML file structures. Still, that approach requires more manual effort and detailed knowledge of the XML schema and Open XML SDK installation. IronXL abstracts these complexities away of working with several different XML files, giving you a much faster path to working with Excel programmatically. How to Install IronXL in Your C# Project? Installing IronXL takes just moments through NuGet Package Manager in Solution Explorer. In Visual Studio, right-click your project and select "Manage NuGet Packages." Search for "IronXL.Excel" and click Install. The package automatically includes all dependencies required for generating Excel files in C#. Alternatively, use the Package Manager Console: Install-Package IronXL.Excel For .NET CLI users working with modern C# projects: dotnet add package IronXL.Excel dotnet add package IronXL.Excel SHELL Verify installation with this simple test to create Excel file programmatically: using IronXL; // new Excel workbook var workbook = WorkBook.Create(); Console.WriteLine("IronXL installed successfully!"); using IronXL; // new Excel workbook var workbook = WorkBook.Create(); Console.WriteLine("IronXL installed successfully!"); IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel This code creates an in-memory workbook object. If it runs without errors, IronXL is ready for use. The library supports all modern .NET versions, ensuring compatibility with your existing projects. For detailed installation guidance and troubleshooting, consult the official documentation. Ready to get started? Download IronXL now and begin generating Excel files in minutes. Output How to Create Your First Excel File? Creating Excel files with IronXL starts with the WorkBook class, your gateway to all Excel operations. The library supports both modern XLSX and legacy XLS formats, giving you flexibility for different requirements when you generate Excel files in C#. using IronXL; // Create a new workbook (XLSX format by default) WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX); // Add metadata workbook.Metadata.Title = "Monthly Sales Report"; workbook.Metadata.Author = "Sales Department"; workbook.Metadata.Comments = "Generated using IronXL"; // Create a worksheet WorkSheet worksheet = workbook.CreateWorkSheet("January Sales"); // Add some basic data worksheet["A1"].Value = "Date"; worksheet["B1"].Value = "Product"; worksheet["C1"].Value = "Quantity"; worksheet["D1"].Value = "Revenue"; // Add data rows worksheet["A2"].Value = new DateTime(2024, 1, 15); worksheet["B2"].Value = "Widget Pro"; worksheet["C2"].Value = 100; worksheet["D2"].Value = 2500.00; // Save the workbook workbook.SaveAs("FirstExcelFile.xlsx"); using IronXL; // Create a new workbook (XLSX format by default) WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX); // Add metadata workbook.Metadata.Title = "Monthly Sales Report"; workbook.Metadata.Author = "Sales Department"; workbook.Metadata.Comments = "Generated using IronXL"; // Create a worksheet WorkSheet worksheet = workbook.CreateWorkSheet("January Sales"); // Add some basic data worksheet["A1"].Value = "Date"; worksheet["B1"].Value = "Product"; worksheet["C1"].Value = "Quantity"; worksheet["D1"].Value = "Revenue"; // Add data rows worksheet["A2"].Value = new DateTime(2024, 1, 15); worksheet["B2"].Value = "Widget Pro"; worksheet["C2"].Value = 100; worksheet["D2"].Value = 2500.00; // Save the workbook workbook.SaveAs("FirstExcelFile.xlsx"); IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel This code demonstrates several key concepts for Excel file generation. The WorkBook.Create() method initializes a new Excel file in memory. You specify the format using the ExcelFileFormat enum - choose XLSX for modern Excel compatibility or XLS for legacy support. The Metadata property allows you to embed document information that appears in Excel's file properties, adhering to Microsoft's document property standards. The CreateWorkSheet() method adds a new sheet with the specified name. Excel's familiar cell notation (A1, B1, etc.) makes setting values intuitive. IronXL automatically handles data type conversion, recognizing dates, numbers, and text without explicit casting. The SaveAs() method writes the complete Excel file to disk. For more worksheet operations, explore the worksheet management tutorial. Output How to Write Data to Excel Cells? IronXL provides multiple approaches for populating Excel cells, from individual cell assignment to bulk range operations. Understanding these methods helps you choose the most efficient approach for your data scenario. WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX); // Create a worksheet WorkSheet worksheet = workbook.CreateWorkSheet("Employees"); // Individual cell assignment worksheet["A1"].Value = "Employee Name"; worksheet["A2"].Value = "John Smith"; worksheet["A3"].Value = "Jane Doe"; // Range assignment for multiple cells worksheet["B1:B3"].Value = "Active"; // Using numeric indices (0-based) worksheet.SetCellValue(0, 2, "Department"); // C1 worksheet.SetCellValue(1, 2, "Sales"); // C2 worksheet.SetCellValue(2, 2, "Marketing"); // C3 // Array-based population string[] headers = { "ID", "Name", "Email", "Phone" }; for (int i = 0; i < headers.Length; i++) { worksheet.SetCellValue(0, i, headers[i]); } // Working with different data types worksheet["E1"].Value = "Salary"; worksheet["E2"].Value = 75000.50m; // Decimal for currency worksheet["E3"].Value = 82000.75m; worksheet["F1"].Value = "Start Date"; worksheet["F2"].Value = new DateTime(2020, 3, 15); worksheet["F3"].Value = new DateTime(2019, 7, 1); worksheet["G1"].Value = "Full Time"; worksheet["G2"].Value = true; // Boolean worksheet["G3"].Value = true; workbook.SaveAs("FirstExcelFile.xlsx"); WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX); // Create a worksheet WorkSheet worksheet = workbook.CreateWorkSheet("Employees"); // Individual cell assignment worksheet["A1"].Value = "Employee Name"; worksheet["A2"].Value = "John Smith"; worksheet["A3"].Value = "Jane Doe"; // Range assignment for multiple cells worksheet["B1:B3"].Value = "Active"; // Using numeric indices (0-based) worksheet.SetCellValue(0, 2, "Department"); // C1 worksheet.SetCellValue(1, 2, "Sales"); // C2 worksheet.SetCellValue(2, 2, "Marketing"); // C3 // Array-based population string[] headers = { "ID", "Name", "Email", "Phone" }; for (int i = 0; i < headers.Length; i++) { worksheet.SetCellValue(0, i, headers[i]); } // Working with different data types worksheet["E1"].Value = "Salary"; worksheet["E2"].Value = 75000.50m; // Decimal for currency worksheet["E3"].Value = 82000.75m; worksheet["F1"].Value = "Start Date"; worksheet["F2"].Value = new DateTime(2020, 3, 15); worksheet["F3"].Value = new DateTime(2019, 7, 1); worksheet["G1"].Value = "Full Time"; worksheet["G2"].Value = true; // Boolean worksheet["G3"].Value = true; workbook.SaveAs("FirstExcelFile.xlsx"); IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel The code shows IronXL's flexible cell addressing. String notation ("A1") feels natural for Excel users, while numeric indices offer programmatic control for loops and dynamic generation. Range assignments ("B1:B3") efficiently set multiple cells to the same value, perfect for initializing columns or applying default values. IronXL intelligently handles different data types. Decimals maintain precision for financial data, DateTime objects format correctly as Excel dates, and booleans appear as TRUE/FALSE. This automatic conversion eliminates manual formatting code while ensuring data integrity. Output For larger datasets, consider this pattern: // Populate from a data source var employees = GetEmployeeData(); // Your data source for (int row = 0; row < employees.Count; row++) { worksheet[$"A{row + 2}"].Value = employees[row].Id; worksheet[$"B{row + 2}"].Value = employees[row].Name; worksheet[$"C{row + 2}"].Value = employees[row].Department; worksheet[$"D{row + 2}"].Value = employees[row].Salary; } // Populate from a data source var employees = GetEmployeeData(); // Your data source for (int row = 0; row < employees.Count; row++) { worksheet[$"A{row + 2}"].Value = employees[row].Id; worksheet[$"B{row + 2}"].Value = employees[row].Name; worksheet[$"C{row + 2}"].Value = employees[row].Department; worksheet[$"D{row + 2}"].Value = employees[row].Salary; } IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel This approach iterates through your data collection, mapping each property to its corresponding column. The string interpolation ($"A{row + 2}") dynamically generates cell addresses, starting from row 2 to preserve headers. How to Apply Professional Formatting? Professional Excel files require more than raw data. IronXL's styling API transforms plain spreadsheets into polished business documents through formatting, colors, and visual hierarchy when you generate Excel files in C#. using IronXL; WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX); // Create a worksheet WorkSheet worksheet = workbook.CreateWorkSheet("Employees"); // Header formatting var headerRange = worksheet["A1:D1"]; headerRange.Style.Font.Bold = true; headerRange.Style.Font.Height = 12; headerRange.Style.SetBackgroundColor("#4472C4"); headerRange.Style.Font.Color = "#FFFFFF"; // Column width adjustment worksheet.AutoSizeColumn(0); // Auto-fit column A worksheet.GetColumn(1).Width = 20; // Set column B to 20 characters // Number formatting var salaryColumn = worksheet["E2:E3"]; salaryColumn.FormatString = "$#,##0.00"; // Date formatting var dateColumn = worksheet["F2:F3"]; dateColumn.FormatString = "MM/dd/yyyy"; // Cell borders var dataRange = worksheet["A1:G3"]; dataRange.Style.TopBorder.Type = IronXL.Styles.BorderType.Thin; dataRange.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin; dataRange.Style.LeftBorder.Type = IronXL.Styles.BorderType.Thin; dataRange.Style.RightBorder.Type = IronXL.Styles.BorderType.Thin; // To set border color, use: dataRange.Style.TopBorder.Color = "#000000"; dataRange.Style.BottomBorder.Color = "#000000"; dataRange.Style.LeftBorder.Color = "#000000"; dataRange.Style.RightBorder.Color = "#000000"; // Text alignment worksheet["A1:G1"].Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center; // Alternating row colors for readability for (int row = 2; row <= 3; row++) { if (row % 2 == 0) { worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2"); } } using IronXL; WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX); // Create a worksheet WorkSheet worksheet = workbook.CreateWorkSheet("Employees"); // Header formatting var headerRange = worksheet["A1:D1"]; headerRange.Style.Font.Bold = true; headerRange.Style.Font.Height = 12; headerRange.Style.SetBackgroundColor("#4472C4"); headerRange.Style.Font.Color = "#FFFFFF"; // Column width adjustment worksheet.AutoSizeColumn(0); // Auto-fit column A worksheet.GetColumn(1).Width = 20; // Set column B to 20 characters // Number formatting var salaryColumn = worksheet["E2:E3"]; salaryColumn.FormatString = "$#,##0.00"; // Date formatting var dateColumn = worksheet["F2:F3"]; dateColumn.FormatString = "MM/dd/yyyy"; // Cell borders var dataRange = worksheet["A1:G3"]; dataRange.Style.TopBorder.Type = IronXL.Styles.BorderType.Thin; dataRange.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin; dataRange.Style.LeftBorder.Type = IronXL.Styles.BorderType.Thin; dataRange.Style.RightBorder.Type = IronXL.Styles.BorderType.Thin; // To set border color, use: dataRange.Style.TopBorder.Color = "#000000"; dataRange.Style.BottomBorder.Color = "#000000"; dataRange.Style.LeftBorder.Color = "#000000"; dataRange.Style.RightBorder.Color = "#000000"; // Text alignment worksheet["A1:G1"].Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center; // Alternating row colors for readability for (int row = 2; row <= 3; row++) { if (row % 2 == 0) { worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2"); } } IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel This formatting code creates a professional appearance that meets enterprise standards. Bold headers with background colors establish visual hierarchy. The SetBackgroundColor() method accepts hex color codes, giving precise control over your color scheme. Font properties include size, color, bold, italic, and underline options, these are all essential for creating Excel files that match corporate branding guidelines. Column width adjustments prevent text truncation. AutoSizeColumn() automatically fits content, while SetColumnWidth() provides exact control. Number formatting uses Excel's format codes. For example, "$#,##0.00" displays currency with thousand separators and two decimal places. Date formatting follows similar patterns, using standard Excel date format strings as documented in Microsoft's Excel specifications. Borders define data boundaries, improving readability. The BorderType enum offers various styles: thin, medium, thick, dotted, and dashed. Alignment options center headers and right-align numbers, following spreadsheet conventions. Alternating row colors, often referred to as "banded rows," help readers track information across wide data sets. Learn more about advanced formatting to create formatted Excel data in our cell styling guide. Output How to Use Excel Formulas Programmatically? Excel formulas bring spreadsheets to life with automatic calculations. IronXL supports formula creation and evaluation, enabling dynamic spreadsheets that update automatically. var workbook = WorkBook.Create(); // Create a budget worksheet WorkSheet budget = workbook.CreateWorkSheet("Q1 Budget"); // Headers budget["A1"].Value = "Category"; budget["B1"].Value = "January"; budget["C1"].Value = "February"; budget["D1"].Value = "March"; budget["E1"].Value = "Q1 Total"; // Budget categories and values string[] categories = { "Salaries", "Marketing", "Operations", "Equipment", "Training" }; decimal[,] monthlyBudgets = { { 50000, 52000, 51000 }, { 15000, 18000, 20000 }, { 8000, 8500, 9000 }, { 12000, 5000, 7000 }, { 3000, 3500, 4000 } }; // Populate data for (int i = 0; i < categories.Length; i++) { budget[$"A{i + 2}"].Value = categories[i]; budget[$"B{i + 2}"].Value = monthlyBudgets[i, 0]; budget[$"C{i + 2}"].Value = monthlyBudgets[i, 1]; budget[$"D{i + 2}"].Value = monthlyBudgets[i, 2]; // Row total formula budget[$"E{i + 2}"].Formula = $"=SUM(B{i + 2}:D{i + 2})"; } // Monthly totals row budget["A7"].Value = "Monthly Total"; budget["B7"].Formula = "=SUM(B2:B6)"; budget["C7"].Formula = "=SUM(C2:C6)"; budget["D7"].Formula = "=SUM(D2:D6)"; budget["E7"].Formula = "=SUM(E2:E6)"; // Calculate percentages budget["A9"].Value = "Marketing %"; budget["B9"].Formula = "=B3/B7*100"; budget["C9"].Formula = "=C3/C7*100"; budget["D9"].Formula = "=D3/D7*100"; // Average calculation budget["A10"].Value = "Average Spending"; budget["B10"].Formula = "=AVERAGE(B2:B6)"; // Evaluate all formulas workbook.EvaluateAll(); workbook.SaveAs("Budget.xlsx"); var workbook = WorkBook.Create(); // Create a budget worksheet WorkSheet budget = workbook.CreateWorkSheet("Q1 Budget"); // Headers budget["A1"].Value = "Category"; budget["B1"].Value = "January"; budget["C1"].Value = "February"; budget["D1"].Value = "March"; budget["E1"].Value = "Q1 Total"; // Budget categories and values string[] categories = { "Salaries", "Marketing", "Operations", "Equipment", "Training" }; decimal[,] monthlyBudgets = { { 50000, 52000, 51000 }, { 15000, 18000, 20000 }, { 8000, 8500, 9000 }, { 12000, 5000, 7000 }, { 3000, 3500, 4000 } }; // Populate data for (int i = 0; i < categories.Length; i++) { budget[$"A{i + 2}"].Value = categories[i]; budget[$"B{i + 2}"].Value = monthlyBudgets[i, 0]; budget[$"C{i + 2}"].Value = monthlyBudgets[i, 1]; budget[$"D{i + 2}"].Value = monthlyBudgets[i, 2]; // Row total formula budget[$"E{i + 2}"].Formula = $"=SUM(B{i + 2}:D{i + 2})"; } // Monthly totals row budget["A7"].Value = "Monthly Total"; budget["B7"].Formula = "=SUM(B2:B6)"; budget["C7"].Formula = "=SUM(C2:C6)"; budget["D7"].Formula = "=SUM(D2:D6)"; budget["E7"].Formula = "=SUM(E2:E6)"; // Calculate percentages budget["A9"].Value = "Marketing %"; budget["B9"].Formula = "=B3/B7*100"; budget["C9"].Formula = "=C3/C7*100"; budget["D9"].Formula = "=D3/D7*100"; // Average calculation budget["A10"].Value = "Average Spending"; budget["B10"].Formula = "=AVERAGE(B2:B6)"; // Evaluate all formulas workbook.EvaluateAll(); workbook.SaveAs("Budget.xlsx"); IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel This budget example illustrates the practical application of formulas. The Formula property accepts standard Excel formula syntax, starting with an equals sign. IronXL supports common functions: SUM, AVERAGE, COUNT, MAX, MIN, and many others. Cell references in formulas work exactly as in Excel, including relative and absolute references. The row total formulas (=SUM(B{i + 2}:D{i + 2})) calculate quarterly totals for each category. String interpolation dynamically generates the correct cell references for each row. Monthly totals sum entire columns, while percentage calculations divide specific cells by totals. The EvaluateAll() method processes all formulas, updating calculated values throughout the workbook. This ensures formulas display results when opened in Excel. Without evaluation, Excel would show the formulas until the user triggers recalculation. Output How to Export Data from Databases to Excel? Real-world applications often export database data to Excel for reporting and analysis. IronXL streamlines this process with built-in DataTable support, eliminating the need for manual field mapping when generating Excel files from C# applications. using System.Data; using System.Data.SqlClient; // Simulate database retrieval (replace with your actual database code) DataTable GetSalesData() { DataTable dt = new DataTable("Sales"); dt.Columns.Add("OrderID", typeof(int)); dt.Columns.Add("CustomerName", typeof(string)); dt.Columns.Add("Product", typeof(string)); dt.Columns.Add("Quantity", typeof(int)); dt.Columns.Add("UnitPrice", typeof(decimal)); dt.Columns.Add("OrderDate", typeof(DateTime)); // Sample data (normally from database) dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99m, DateTime.Now.AddDays(-5)); dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99m, DateTime.Now.AddDays(-4)); dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99m, DateTime.Now.AddDays(-3)); dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99m, DateTime.Now.AddDays(-2)); dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99m, DateTime.Now.AddDays(-1)); return dt; } // Export to Excel WorkBook reportWorkbook = WorkBook.Create(); WorkSheet reportSheet = reportWorkbook.CreateWorkSheet("Sales Report"); // Get data from database DataTable salesData = GetSalesData(); // Method 1: Manual mapping with formatting reportSheet["A1"].Value = "Order Report - " + DateTime.Now.ToString("MMMM yyyy"); reportSheet.Merge("A1:F1"); reportSheet["A1"].Style.Font.Bold = true; reportSheet["A1"].Style.Font.Height = 14; // Headers int headerRow = 3; for (int col = 0; col < salesData.Columns.Count; col++) { reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns[col].ColumnName); } // Format headers var headers = reportSheet[$"A{headerRow}:F{headerRow}"]; headers.Style.Font.Bold = true; headers.Style.SetBackgroundColor("#D9E1F2"); // Data rows for (int row = 0; row < salesData.Rows.Count; row++) { for (int col = 0; col < salesData.Columns.Count; col++) { reportSheet.SetCellValue(row + headerRow, col, salesData.Rows[row][col]); } // Add total column with formula reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}"; } // Add total header and format reportSheet["G3"].Value = "Total"; reportSheet["G3"].Style.Font.Bold = true; reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2"); // Format currency columns reportSheet[$"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00"; reportSheet[$"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00"; // Format date column reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy"; // Add summary section int summaryRow = headerRow + salesData.Rows.Count + 2; reportSheet[$"A{summaryRow}"].Value = "Summary"; reportSheet[$"A{summaryRow}"].Style.Font.Bold = true; reportSheet[$"A{summaryRow + 1}"].Value = "Total Orders:"; reportSheet[$"B{summaryRow + 1}"].Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})"; reportSheet[$"A{summaryRow + 2}"].Value = "Total Revenue:"; reportSheet[$"B{summaryRow + 2}"].Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})"; reportSheet[$"B{summaryRow + 2}"].FormatString = "$#,##0.00"; // Auto-fit columns for (int col = 0; col <= 6; col++) { reportSheet.AutoSizeColumn(col); } // Evaluate formulas and save reportWorkbook.EvaluateAll(); reportWorkbook.SaveAs("DatabaseExport.xlsx"); using System.Data; using System.Data.SqlClient; // Simulate database retrieval (replace with your actual database code) DataTable GetSalesData() { DataTable dt = new DataTable("Sales"); dt.Columns.Add("OrderID", typeof(int)); dt.Columns.Add("CustomerName", typeof(string)); dt.Columns.Add("Product", typeof(string)); dt.Columns.Add("Quantity", typeof(int)); dt.Columns.Add("UnitPrice", typeof(decimal)); dt.Columns.Add("OrderDate", typeof(DateTime)); // Sample data (normally from database) dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99m, DateTime.Now.AddDays(-5)); dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99m, DateTime.Now.AddDays(-4)); dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99m, DateTime.Now.AddDays(-3)); dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99m, DateTime.Now.AddDays(-2)); dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99m, DateTime.Now.AddDays(-1)); return dt; } // Export to Excel WorkBook reportWorkbook = WorkBook.Create(); WorkSheet reportSheet = reportWorkbook.CreateWorkSheet("Sales Report"); // Get data from database DataTable salesData = GetSalesData(); // Method 1: Manual mapping with formatting reportSheet["A1"].Value = "Order Report - " + DateTime.Now.ToString("MMMM yyyy"); reportSheet.Merge("A1:F1"); reportSheet["A1"].Style.Font.Bold = true; reportSheet["A1"].Style.Font.Height = 14; // Headers int headerRow = 3; for (int col = 0; col < salesData.Columns.Count; col++) { reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns[col].ColumnName); } // Format headers var headers = reportSheet[$"A{headerRow}:F{headerRow}"]; headers.Style.Font.Bold = true; headers.Style.SetBackgroundColor("#D9E1F2"); // Data rows for (int row = 0; row < salesData.Rows.Count; row++) { for (int col = 0; col < salesData.Columns.Count; col++) { reportSheet.SetCellValue(row + headerRow, col, salesData.Rows[row][col]); } // Add total column with formula reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}"; } // Add total header and format reportSheet["G3"].Value = "Total"; reportSheet["G3"].Style.Font.Bold = true; reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2"); // Format currency columns reportSheet[$"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00"; reportSheet[$"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00"; // Format date column reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy"; // Add summary section int summaryRow = headerRow + salesData.Rows.Count + 2; reportSheet[$"A{summaryRow}"].Value = "Summary"; reportSheet[$"A{summaryRow}"].Style.Font.Bold = true; reportSheet[$"A{summaryRow + 1}"].Value = "Total Orders:"; reportSheet[$"B{summaryRow + 1}"].Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})"; reportSheet[$"A{summaryRow + 2}"].Value = "Total Revenue:"; reportSheet[$"B{summaryRow + 2}"].Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})"; reportSheet[$"B{summaryRow + 2}"].FormatString = "$#,##0.00"; // Auto-fit columns for (int col = 0; col <= 6; col++) { reportSheet.AutoSizeColumn(col); } // Evaluate formulas and save reportWorkbook.EvaluateAll(); reportWorkbook.SaveAs("DatabaseExport.xlsx"); IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel This comprehensive example demonstrates a complete database-to-Excel workflow for generating Excel files in C #. The DataTable simulates database retrieval - in production, replace this with your actual database queries using Entity Framework, Dapper, or ADO.NET. The manual mapping approach gives complete control over formatting and layout, as recommended by Microsoft's data export best practices. The code creates a professional report with a title, formatted headers, and data rows. Formula columns calculate line totals dynamically. The summary section utilizes Excel formulas to count orders and sum revenue, ensuring that these values are updated if the data changes. Currency and date formatting follow business document standards, while auto-sizing columns ensures all content displays properly. For handling larger datasets, explore our performance optimization guide. Output Need to streamline your Excel reporting? Get a license to unlock IronXL's full potential for production deployments. How to Handle Multiple Worksheets? Complex Excel files often require multiple worksheets to organize related data. IronXL simplifies multi-sheet management with intuitive methods for creating, accessing, and organizing worksheets. // Create a multi-sheet workbook WorkBook companyReport = WorkBook.Create(); // Create department sheets WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales"); WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory"); WorkSheet hrSheet = companyReport.CreateWorkSheet("HR Metrics"); // Populate Sales sheet salesSheet["A1"].Value = "Sales Dashboard"; salesSheet["A3"].Value = "Region"; salesSheet["B3"].Value = "Q1 Sales"; salesSheet["C3"].Value = "Q2 Sales"; string[] regions = { "North", "South", "East", "West" }; decimal[] q1Sales = { 250000, 180000, 220000, 195000 }; decimal[] q2Sales = { 275000, 195000, 240000, 210000 }; for (int i = 0; i < regions.Length; i++) { salesSheet[$"A{i + 4}"].Value = regions[i]; salesSheet[$"B{i + 4}"].Value = q1Sales[i]; salesSheet[$"C{i + 4}"].Value = q2Sales[i]; } // Populate Inventory sheet inventorySheet["A1"].Value = "Inventory Status"; inventorySheet["A3"].Value = "Product"; inventorySheet["B3"].Value = "Stock Level"; inventorySheet["C3"].Value = "Reorder Point"; inventorySheet["D3"].Value = "Status"; // Add inventory data with conditional status string[] products = { "Widget A", "Widget B", "Widget C" }; int[] stock = { 150, 45, 200 }; int[] reorderPoint = { 100, 50, 75 }; for (int i = 0; i < products.Length; i++) { inventorySheet[$"A{i + 4}"].Value = products[i]; inventorySheet[$"B{i + 4}"].Value = stock[i]; inventorySheet[$"C{i + 4}"].Value = reorderPoint[i]; // Status based on stock level string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK"; inventorySheet[$"D{i + 4}"].Value = status; // Color code status if (status == "REORDER") { inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000"; } } // Create summary sheet referencing other sheets WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary"); summarySheet["A1"].Value = "Company Overview"; summarySheet["A3"].Value = "Metric"; summarySheet["B3"].Value = "Value"; summarySheet["A4"].Value = "Total Q1 Sales"; summarySheet["B4"].Formula = "=SUM(Sales!B4:B7)"; summarySheet["A5"].Value = "Total Q2 Sales"; summarySheet["B5"].Formula = "=SUM(Sales!C4:C7)"; summarySheet["A6"].Value = "Products Need Reorder"; summarySheet["B6"].Formula = "=COUNTIF(Inventory!D4:D6,\"REORDER\")"; // Format all sheets consistently foreach (WorkSheet sheet in companyReport.WorkSheets) { // Format headers sheet["A1"].Style.Font.Bold = true; sheet["A1"].Style.Font.Height = 14; var headerRow = sheet["A3:D3"]; headerRow.Style.Font.Bold = true; headerRow.Style.SetBackgroundColor("#E7E6E6"); } // Save multi-sheet workbook companyReport.SaveAs("CompanyReport.xlsx"); // Create a multi-sheet workbook WorkBook companyReport = WorkBook.Create(); // Create department sheets WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales"); WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory"); WorkSheet hrSheet = companyReport.CreateWorkSheet("HR Metrics"); // Populate Sales sheet salesSheet["A1"].Value = "Sales Dashboard"; salesSheet["A3"].Value = "Region"; salesSheet["B3"].Value = "Q1 Sales"; salesSheet["C3"].Value = "Q2 Sales"; string[] regions = { "North", "South", "East", "West" }; decimal[] q1Sales = { 250000, 180000, 220000, 195000 }; decimal[] q2Sales = { 275000, 195000, 240000, 210000 }; for (int i = 0; i < regions.Length; i++) { salesSheet[$"A{i + 4}"].Value = regions[i]; salesSheet[$"B{i + 4}"].Value = q1Sales[i]; salesSheet[$"C{i + 4}"].Value = q2Sales[i]; } // Populate Inventory sheet inventorySheet["A1"].Value = "Inventory Status"; inventorySheet["A3"].Value = "Product"; inventorySheet["B3"].Value = "Stock Level"; inventorySheet["C3"].Value = "Reorder Point"; inventorySheet["D3"].Value = "Status"; // Add inventory data with conditional status string[] products = { "Widget A", "Widget B", "Widget C" }; int[] stock = { 150, 45, 200 }; int[] reorderPoint = { 100, 50, 75 }; for (int i = 0; i < products.Length; i++) { inventorySheet[$"A{i + 4}"].Value = products[i]; inventorySheet[$"B{i + 4}"].Value = stock[i]; inventorySheet[$"C{i + 4}"].Value = reorderPoint[i]; // Status based on stock level string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK"; inventorySheet[$"D{i + 4}"].Value = status; // Color code status if (status == "REORDER") { inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000"; } } // Create summary sheet referencing other sheets WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary"); summarySheet["A1"].Value = "Company Overview"; summarySheet["A3"].Value = "Metric"; summarySheet["B3"].Value = "Value"; summarySheet["A4"].Value = "Total Q1 Sales"; summarySheet["B4"].Formula = "=SUM(Sales!B4:B7)"; summarySheet["A5"].Value = "Total Q2 Sales"; summarySheet["B5"].Formula = "=SUM(Sales!C4:C7)"; summarySheet["A6"].Value = "Products Need Reorder"; summarySheet["B6"].Formula = "=COUNTIF(Inventory!D4:D6,\"REORDER\")"; // Format all sheets consistently foreach (WorkSheet sheet in companyReport.WorkSheets) { // Format headers sheet["A1"].Style.Font.Bold = true; sheet["A1"].Style.Font.Height = 14; var headerRow = sheet["A3:D3"]; headerRow.Style.Font.Bold = true; headerRow.Style.SetBackgroundColor("#E7E6E6"); } // Save multi-sheet workbook companyReport.SaveAs("CompanyReport.xlsx"); IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel This example creates a complete multi-sheet report. Each worksheet serves a specific purpose: sales data, inventory tracking, and HR metrics. The summary sheet consolidates key metrics using cross-sheet formulas. Notice the sheet reference syntax in formulas "Sales!B4:B7" refers to cells B4 through B7 on the Sales sheet. The inventory sheet demonstrates conditional logic, coloring low-stock items red for immediate attention. The foreach loop applies consistent formatting across all sheets, maintaining a professional appearance throughout the workbook. Sheet names appear as tabs in Excel, allowing users to easily navigate between different data views. What Are the Best Practices for Excel Generation? Efficient Excel file generation in C# requires thoughtful approaches to memory usage, error handling, and deployment. These practices ensure your applications scale effectively while maintaining reliability when creating Excel spreadsheets programmatically. Memory management becomes critical with large files. Instead of loading entire datasets into memory, process data in chunks: // Process large datasets efficiently public void ExportLargeDataset(string filename) { WorkBook workbook = WorkBook.Create(); WorkSheet sheet = workbook.CreateWorkSheet("Data"); int rowsPerBatch = 1000; int currentRow = 1; // Process in batches foreach (var batch in GetDataInBatches(rowsPerBatch)) { foreach (var record in batch) { sheet[$"A{currentRow}"].Value = record.Id; sheet[$"B{currentRow}"].Value = record.Name; sheet[$"C{currentRow}"].Value = record.Value; currentRow++; } } workbook.SaveAs(filename); } // Process large datasets efficiently public void ExportLargeDataset(string filename) { WorkBook workbook = WorkBook.Create(); WorkSheet sheet = workbook.CreateWorkSheet("Data"); int rowsPerBatch = 1000; int currentRow = 1; // Process in batches foreach (var batch in GetDataInBatches(rowsPerBatch)) { foreach (var record in batch) { sheet[$"A{currentRow}"].Value = record.Id; sheet[$"B{currentRow}"].Value = record.Name; sheet[$"C{currentRow}"].Value = record.Value; currentRow++; } } workbook.SaveAs(filename); } IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel Error handling prevents application crashes and provides meaningful feedback when generating Excel files: try { WorkBook workbook = WorkBook.Create(); // Excel generation code workbook.SaveAs("output.xlsx"); } catch (Exception ex) { // Log the error Console.WriteLine($"Excel generation failed: {ex.Message}"); // Implement appropriate recovery or notification } try { WorkBook workbook = WorkBook.Create(); // Excel generation code workbook.SaveAs("output.xlsx"); } catch (Exception ex) { // Log the error Console.WriteLine($"Excel generation failed: {ex.Message}"); // Implement appropriate recovery or notification } IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel For web applications, generate Excel files in memory and stream to users: // ASP.NET Core example public IActionResult DownloadExcel() { WorkBook workbook = GenerateReport(); var stream = new MemoryStream(); workbook.SaveAs(stream); stream.Position = 0; return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "report.xlsx"); } // ASP.NET Core example public IActionResult DownloadExcel() { WorkBook workbook = GenerateReport(); var stream = new MemoryStream(); workbook.SaveAs(stream); stream.Position = 0; return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "report.xlsx"); } IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel Deployment considerations ensure smooth production operations. IronXL works in restricted environments without elevated permissions, making it suitable for shared hosting and containerized deployments. Include the IronXL license file in your deployment package, and ensure your application has write permissions for temporary file operations if needed. For additional deployment guidance, consult the deployment documentation. Conclusion IronXL transforms Excel file generation in C# from a complex challenge into straightforward coding. You've learned to create workbooks, populate cells, apply formatting, use formulas, and export database data - all without Microsoft Office dependencies. These techniques for generating Excel files programmatically work consistently across Windows, Linux, and cloud platforms. Ready to implement Excel generation in your C# applications? Start your free trial or explore the comprehensive API documentation for advanced features. For production deployments, view licensing options that match your project requirements. 常见问题解答 什么是 IronXL? IronXL是一个库,允许开发人员在C#中创建、读取和编辑Excel文件,而不需要Microsoft Office或复杂的COM Interop。 如何使用C#生成Excel文件? 你可以使用IronXL在C#中生成Excel文件,它提供了一个简单的API来创建、格式化和编程操作Excel文件。 我需要安装 Microsoft Office 来使用 IronXL 吗? 不,IronXL不需要在你的系统上安装Microsoft Office,是一个轻量级的创建和编辑Excel文件的解决方案。 IronXL可以处理高级Excel格式化吗? 是的,IronXL支持高级格式选项,允许你在电子表格中应用样式、格式和其他Excel功能。 是否可以通过IronXL将数据库与Excel文件集成? 是的,IronXL使你能够将Excel文件与数据库集成,方便如数据导出和直接从C#应用程序报告的任务。 IronXL可以处理哪些文件格式? IronXL可以处理XLS和XLSX文件格式,提供了处理Excel文件的灵活性。 我可以用IronXL自动化电子表格生成吗? 是的,IronXL允许你自动化生成电子表格,非常适合如报告创建和数据导出等任务。 IronXL支持.NET应用程序吗? IronXL完全兼容.NET应用程序,允许在你的C#项目中无缝集成和功能。 IronXL 的一些常见用例是什么? IronXL的常见用例包括创建报表、导出数据、自动化电子表格任务,以及在.NET应用程序中集成Excel功能。 IronXL如何简化C#中的Excel文件创建? IronXL通过提供一个简单直观的API简化Excel文件创建,消除复杂设置和依赖,简化开发过程。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已发布十月 27, 2025 如何在 C# 中创建 Excel 数据透视表 学习通过这个清晰的分步指南使用C# Interop和IronXL在Excel中创建数据透视表。 阅读更多 已发布十月 27, 2025 如何在C#中将DataGridView导出到包含列头的Excel 学习如何在将DataGridView数据导出到Excel时保留列头。使用IronXL库的C#逐步教程。 阅读更多 已发布十月 27, 2025 如何在.NET Core中使用CSV Reader与IronXL 学习通过实际示例有效地使用IronXL作为.NET Core的CSV读取器。 阅读更多 如何在 C# 中写入 CSV 文件如何在 C# 中使用 IronXL 创...
已发布十月 27, 2025 如何在C#中将DataGridView导出到包含列头的Excel 学习如何在将DataGridView数据导出到Excel时保留列头。使用IronXL库的C#逐步教程。 阅读更多