using Microsoft.AspNetCore.Hosting; using OfficeOpenXml; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZR.Infrastructure.Helper { /// /// Excel 导出帮助类(EPPlus) /// public class ExcelHelper { private readonly IWebHostEnvironment _webHostEnvironment; /// /// 构造函数,需要注入 IWebHostEnvironment 获取 web 根目录 /// /// public ExcelHelper(IWebHostEnvironment webHostEnvironment) { _webHostEnvironment = webHostEnvironment; ExcelPackage.License.SetNonCommercialPersonal("pnaa"); } /// /// 导出 Excel 文件 /// /// 数据类型 /// 数据列表 /// Sheet 名 /// 文件名,不含时间戳和后缀 /// 返回文件名和完整路径 public (string, string) ExportExcel(List list, string sheetName, string fileName) { // 生成带时间戳的文件名 string sFileName = $"{fileName}_{DateTime.Now:MMdd_HHmmss}.xlsx"; string fullPath = Path.Combine(_webHostEnvironment.WebRootPath, "export", sFileName); // 创建目录 Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); using (var package = new ExcelPackage()) { // 添加 Sheet var worksheet = package.Workbook.Worksheets.Add(sheetName ?? "Sheet1"); // 将 List 导入到 Sheet worksheet.Cells["A2"].LoadFromCollection(list, false); // true 表示包含表头 // 插入图片 var pic = worksheet.Drawings.AddPicture("Logo", new FileInfo("D:\\CodeManage\\Zr.Admin.NET\\ZR.Admin.WebApi\\wwwroot\\workfiles\\2025\\20250818\\当日照片\\1755531044_7059.jpg")); // 设置图片位置 pic.SetPosition(4, 0, 4, 0); // 行, 行偏移, 列, 列偏移 pic.SetSize(100, 50); // 宽高像素 // 自动调整列宽 worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(); // 保存文件 package.SaveAs(new FileInfo(fullPath)); } return (sFileName, fullPath); } } }