如何基于C#应用程序生成含表格与页眉的PDF或Excel文件?
Hey there! Creating a C# app that generates PDFs and Excel files with tables and headers is totally manageable with the right libraries. I’ll walk you through both tasks with practical code examples so you can hit the ground running.
I’d recommend using iTextSharp (a popular, battle-tested library for PDF generation). If you’re targeting .NET Core/.NET 5+, use the iTextSharp.LGPLv2.Core NuGet package instead for better compatibility.
First, install the appropriate NuGet package:
// For .NET Framework Install-Package iTextSharp // For .NET Core/.NET 5+ Install-Package iTextSharp.LGPLv2.Core
To add persistent headers across all pages, you’ll need a custom PageEventHelper to handle header rendering. Here’s a complete example that includes both a header and a formatted table:
using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class PdfGenerator { public void GeneratePdf(string outputPath) { // Initialize a new A4 document with custom margins Document document = new Document(PageSize.A4, 50, 50, 70, 70); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create)); // Attach our custom header handler writer.PageEvent = new CustomHeaderHandler(); document.Open(); // Add a title to the first page (optional) document.Add(new Paragraph("Sample PDF with Table & Persistent Header")); document.Add(Chunk.NEWLINE); // Create a 3-column table that fills the page width PdfPTable dataTable = new PdfPTable(3); dataTable.WidthPercentage = 100; // Add bold column headers dataTable.AddCell(new Phrase("ID", FontFactory.GetFont(FontFactory.HELVETICA_BOLD))); dataTable.AddCell(new Phrase("Full Name", FontFactory.GetFont(FontFactory.HELVETICA_BOLD))); dataTable.AddCell(new Phrase("Contact Email", FontFactory.GetFont(FontFactory.HELVETICA_BOLD))); // Populate table with sample data dataTable.AddCell("1"); dataTable.AddCell("John Doe"); dataTable.AddCell("john.doe@example.com"); dataTable.AddCell("2"); dataTable.AddCell("Jane Smith"); dataTable.AddCell("jane.smith@example.com"); // Add the table to the document document.Add(dataTable); document.Close(); } } // Custom class to render headers on every page public class CustomHeaderHandler : PdfPageEventHelper { public override void OnEndPage(PdfWriter writer, Document document) { // Create a single-column table for the header PdfPTable headerTable = new PdfPTable(1); headerTable.WidthPercentage = 100; // Add header text with bold styling headerTable.AddCell(new Phrase("My Application - Generated Report", FontFactory.GetFont(FontFactory.HELVETICA, 12, Font.BOLD))); // Position the header at the top of the page (adjust coordinates as needed) headerTable.WriteSelectedRows(0, -1, document.LeftMargin, document.Top + 20, writer.DirectContent); } }
This code creates a PDF with a bold header on every page and a clean data table with styled column headers. Tweak margins, fonts, or table sizing to match your app’s design.
For Excel generation, EPPlus is my go-to—it’s intuitive and handles tables and headers seamlessly. Note: EPPlus requires a commercial license for commercial use; if you need a free open-source alternative, check out NPOI.
First, install the EPPlus NuGet package:
Install-Package EPPlus
Here’s an example that generates an Excel file with a centered top header, styled table headers, and an auto-formatted data table:
using System.IO; using OfficeOpenXml; using OfficeOpenXml.Style; public class ExcelGenerator { public void GenerateExcel(string outputPath) { // Set license context (required for EPPlus v5+) ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // Use LicenseContext.Commercial for commercial apps using (ExcelPackage excelPackage = new ExcelPackage()) { // Create a new worksheet ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("User Data"); // Add a top header (merged across columns) worksheet.Cells["A1"].Value = "My Application - User Report"; worksheet.Cells["A1"].Style.Font.Bold = true; worksheet.Cells["A1"].Style.Font.Size = 14; worksheet.Cells["A1:C1"].Merge = true; worksheet.Cells["A1:C1"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; // Add table column headers (row 3) worksheet.Cells["A3"].Value = "ID"; worksheet.Cells["B3"].Value = "Full Name"; worksheet.Cells["C3"].Value = "Contact Email"; // Style table headers with gray background and bold text var headerRange = worksheet.Cells["A3:C3"]; headerRange.Style.Font.Bold = true; headerRange.Style.Fill.PatternType = ExcelFillStyle.Solid; headerRange.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray); // Populate table with sample data worksheet.Cells["A4"].Value = 1; worksheet.Cells["B4"].Value = "John Doe"; worksheet.Cells["C4"].Value = "john.doe@example.com"; worksheet.Cells["A5"].Value = 2; worksheet.Cells["B5"].Value = "Jane Smith"; worksheet.Cells["C5"].Value = "jane.smith@example.com"; // Create an official Excel table (adds filtering/sorting out of the box) var dataTable = worksheet.Tables.Add(worksheet.Cells["A3:C5"], "UserTable"); dataTable.TableStyle = TableStyles.Medium2; // Apply a built-in stylish format // Auto-fit columns to content for better readability worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(); // Save the final Excel file excelPackage.SaveAs(new FileInfo(outputPath)); } } }
This example produces an Excel file with a polished layout: a centered top title, styled column headers, and a formatted data table with built-in styling. Adjust table styles, fonts, or cell merging to fit your needs.
内容的提问来源于stack exchange,提问作者Aleksa Djuric




