using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using MiniExcelLibs; namespace IRaCIS.Core.Application.Service; public static class ExcelExportHelper { //MiniExcel_Export public static async Task DataExportAsync(string code, object data, string exportFileNamePrefix, IRepository _commonDocumentRepository, IWebHostEnvironment _hostEnvironment) { var doc = _commonDocumentRepository.AsQueryable(true).FirstOrDefault(t => t.Code == code); if (doc == null) { throw new Exception("当前code 没要找到对应的导出模板文件"); } var rootPath = Directory.GetParent(_hostEnvironment.ContentRootPath.TrimEnd('\\'))?.FullName; var filePath = Path.Combine(rootPath, doc.Path.Trim('/')); if (!System.IO.File.Exists(filePath)) { throw new Exception("服务器本地不存在该路径文件"); } //模板路径 var tplPath = filePath; #region MiniExcel var memoryStream = new MemoryStream(); await MiniExcel.SaveAsByTemplateAsync(memoryStream, tplPath, data); memoryStream.Seek(0, SeekOrigin.Begin); return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = $"{exportFileNamePrefix}_{doc.Name.Substring(0,doc.Name.LastIndexOf('.'))}——{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx" }; #endregion #region Magicodes 模板规则不一样 ////创建Excel导出对象 //IExportFileByTemplate exporter = new ExcelExporter(); ////根据模板导出 //var result = await exporter.ExportBytesByTemplate(exportInfo, tplPath); //return new XlsxFileResult(bytes: result, fileDownloadName: $"{doc.Name}_{DateTime.Now.ToString("yyyy-MM-dd:hh:mm:ss")}.xlsx"); #endregion } }