如何基于.NET Framework 4.5及以上版本,不使用第三方DLL导出Excel?
Absolutely! You don't need any third-party libraries to export data to Excel-compatible files using .NET Framework 4.5 or later. Below are two robust, dependency-free approaches tailored to different needs:
1. Export to CSV (Simplest, Universal Option)
CSV files are natively supported by Excel (and almost all spreadsheet tools), and this method relies solely on core .NET Framework libraries. It’s fast, lightweight, and perfect for raw data export where complex formatting isn’t required.
Here’s a practical code example to export a list of objects to CSV:
using System.IO; using System.Collections.Generic; public class Employee { public string FullName { get; set; } public int EmployeeId { get; set; } public string Department { get; set; } } public void ExportEmployeesToCsv(List<Employee> employees, string outputPath) { using (var writer = new StreamWriter(outputPath)) { // Write header row writer.WriteLine("Full Name,Employee ID,Department"); // Write data rows, escaping special characters to avoid formatting errors foreach (var emp in employees) { string escapedName = $"\"{emp.FullName.Replace("\"", "\"\"")}\""; string escapedDept = $"\"{emp.Department.Replace("\"", "\"\"")}\""; writer.WriteLine($"{escapedName},{emp.EmployeeId},{escapedDept}"); } } }
Note: CSV doesn’t support advanced features like cell styling, formulas, or multiple worksheets, but it’s ideal for quick, reliable data exports.
2. Export to XLSX (True Excel Format, No External Dependencies)
If you need a proper .xlsx file with support for sheets, formatting, or formulas, you can use the System.IO.Packaging namespace (included with .NET Framework) to manually build the XLSX structure—since XLSX files are essentially zip archives containing XML data.
You’ll need to add a reference to WindowsBase.dll (it’s part of the standard .NET Framework installation, so no external downloads are needed). Here’s a minimal example to create a single-sheet XLSX file:
using System.IO; using System.IO.Packaging; using System.Xml; public void CreateBasicXlsx(string outputPath) { // Create the zip package (the foundation of an XLSX file) using (var package = Package.Open(outputPath, FileMode.Create)) { // Add all required XML parts to the package AddContentTypePart(package); AddWorkbookPart(package); AddWorksheetPart(package); AddSharedStringsPart(package); } } // Helper method to define content types for the XLSX package private void AddContentTypePart(Package package) { var contentTypePart = package.CreatePart( new Uri("/[Content_Types].xml", UriKind.Relative), "application/vnd.openxmlformats-package.core-properties+xml"); using (var writer = XmlWriter.Create(contentTypePart.GetStream())) { writer.WriteStartDocument(); writer.WriteStartElement("Types", "http://schemas.openxmlformats.org/package/2006/content-types"); writer.WriteElementString("Default", null, "Extension=\"xml\" ContentType=\"application/xml\""); writer.WriteElementString("Default", null, "Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\""); writer.WriteElementString("Override", null, "PartName=\"/xl/workbook.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\""); writer.WriteElementString("Override", null, "PartName=\"/xl/worksheets/sheet1.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\""); writer.WriteElementString("Override", null, "PartName=\"/xl/sharedStrings.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml\""); writer.WriteEndElement(); writer.WriteEndDocument(); } } // Add other helper methods (workbook, worksheet, shared strings) to populate data // For a complete implementation, you'd extend this to write your actual data rows
Note: Manually building XLSX requires more boilerplate code, but it gives you full control over the file structure. If you want to skip some of the XML setup without adding third-party DLLs, you can also use the official Open XML SDK (a Microsoft-maintained NuGet package)—though strictly speaking, it’s an external dependency, it’s fully supported by Microsoft.
Honorable Mention: Microsoft.Office.Interop.Excel
If your target environment has Microsoft Excel installed, you can use the Interop libraries (included with .NET Framework) to automate Excel directly. This lets you create fully formatted workbooks with formulas and macros, but it requires Excel to be present on the machine running the code—making it unsuitable for server-side applications.
内容的提问来源于stack exchange,提问作者Satya Sahoo

