.NETAdmin/Infrastructure/Helper/ExcelHelper.cs
2025-08-19 23:49:57 +08:00

79 lines
2.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
{
/// <summary>
/// Excel 导出帮助类EPPlus
/// </summary>
public class ExcelHelper
{
private readonly IWebHostEnvironment _webHostEnvironment;
/// <summary>
/// 构造函数,需要注入 IWebHostEnvironment 获取 web 根目录
/// </summary>
/// <param name="webHostEnvironment"></param>
public ExcelHelper(IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment = webHostEnvironment;
ExcelPackage.License.SetNonCommercialPersonal("pnaa");
}
/// <summary>
/// 导出 Excel 文件
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="list">数据列表</param>
/// <param name="sheetName">Sheet 名</param>
/// <param name="fileName">文件名,不含时间戳和后缀</param>
/// <returns>返回文件名和完整路径</returns>
public (string, string) ExportExcel<T>(List<T> 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<T> 导入到 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);
}
}
}