基于 EPPlus 库将数据写入 Excel 文件,支持自定义表头和数据。 using OfficeOpenXml; public class ExcelWriter { public static bool WriteExcel(string filePath, List<string> headers, List<List<object>> data) { try { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); // 写入表头 for (int col = 0; col < headers.Count; col++) { worksheet.Cells[1, col + 1].Value = headers[col]; worksheet.Cells[1, col + 1].Style.Font.Bold = true; } // 写入数据 for (int row = 0; row < data.Count; row++) { var rowData = data[row]; for (int col = 0; col < rowData.Count; col++) { worksheet.Cells[row + 2, col + 1].Value = rowData[col]; } } // 自动调整列宽 worksheet.Cells.AutoFitColumns(); // 保存文件 File.WriteAllBytes(filePath, package.GetAsByteArray()); } Console.WriteLine("Excel写入成功!"); return true; } catch (Exception ex) { Console.WriteLine($"写入失败: {ex.Message}"); return false; } } // 调用示例 public static void TestExcelWriter() { var headers = new List<string> { "姓名", "年龄", "职业" }; var data = new List<List<object>> { new List<object> { "张三", 25, "程序员" }, new List<object> { "李四", 30, "设计师" } }; WriteExcel("output.xlsx", headers, data); } }