irc-netcore-api/IRaCIS.Core.Application/Helper/ExcelExportHelper.cs

59 lines
2.0 KiB
C#

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<IActionResult> DataExportAsync(string code, object data, string exportFileNamePrefix, IRepository<CommonDocument> _commonDocumentRepository, IWebHostEnvironment _hostEnvironment)
{
var doc = _commonDocumentRepository.AsQueryable(true).FirstOrDefault(t => t.Code == code);
if (doc == null)
{
throw new Exception("程序没有找到对应的数据模板文件,请联系系统运维人员。");
}
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
}
}