using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Npoi.Mapper; using System.IO; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using WMS.Web.Domain.IService; using WMS.Web.Domain.Options; using WMS.Web.Domain.Entitys; using WMS.Web.Domain.Values; using WMS.Web.Domain.Infrastructure; using WMS.Web.Core.Dto; namespace WMS.Web.Domain.Services { public class ExportExcelService : IExportExcelService { private readonly IQiniuUploadService _qiniuUploadService; private readonly IServiceScopeFactory _serviceScopeFactory; private readonly ILogger _logger; private readonly QiniuOptions _option; public ExportExcelService(IQiniuUploadService qiniuUploadService, IServiceScopeFactory serviceScopeFactory, ILogger logger, IOptions option) { _qiniuUploadService = qiniuUploadService; _serviceScopeFactory = serviceScopeFactory; _logger = logger; _option = option?.Value; } /// /// 列表页导出 /// /// /// /// /// /// /// /// /// public async Task Export(List dataList, string fileName, int userId, int companyId, FileDownLoadOrderType type, Mapper mapper = null, int? supplierId = null) { FileDownManager entity = new FileDownManager(userId, companyId, type, _option.Url + fileName, supplierId); using (var scope = _serviceScopeFactory.CreateScope()) { var _fileDownManagerService = scope.ServiceProvider.GetRequiredService(); entity = await _fileDownManagerService.Add(entity); List> listz = new List>(); listz.Add(dataList); string msg = await Upload(listz, fileName, userId, type); entity.Finish(string.IsNullOrEmpty(msg) == true ? true : false, msg); await _fileDownManagerService.Edit(entity); return; } } /// /// 全字段导出 /// /// /// /// /// /// /// /// /// /// public Task ExportAll(Request request, string fileName, int userId, int companyId, FileDownLoadOrderType type, Mapper mapper = null, int? supplierId = null) where Request : PaginationBaseRequestDto { return Task.CompletedTask; //FileDownManager entity = new FileDownManager(userId, companyId, type, _option.Url + fileName, supplierId); //request.PageNo = 1; //request.PageSize = _option.PageSize; //List> listz = new List>(); //string msg = ""; //using (var scope = _serviceScopeFactory.CreateScope()) //{ // var _fileDownManagerService = scope.ServiceProvider.GetRequiredService(); // entity = await _fileDownManagerService.Add(entity); // try // { // var _service = scope.ServiceProvider.GetRequiredService>(); // _logger.LogInformation($"{DateTime.Now}--开始访问数据"); // var (obj, total) = await _service.GetListAllField(request, companyId); // var list = (List)obj; // var page = Math.Ceiling(Convert.ToDecimal(total) / _option.PageSize); // listz.Add(list); // for (int i = 1; i < page; i++) // { // request.PageNo++; // var (obj_f, total_f) = await _service.GetListAllField(request, companyId); // var list_f = (List)obj_f; // listz.Add(list_f); // } // _logger.LogInformation($"{DateTime.Now}--访问数据成功 总数:{total}"); // } // catch (Exception ex) // { // msg = $"未找到数据 {ex.ToString()}"; // _logger.LogError($"导出异常:{ex.ToString()}"); // } // if (!string.IsNullOrEmpty(msg)) // { // entity.Finish(false, msg); // await _fileDownManagerService.Edit(entity); // return; // } // msg = await Upload(listz, fileName, userId, type); // entity.Finish(string.IsNullOrEmpty(msg) == true ? true : false, msg); // await _fileDownManagerService.Edit(entity); // return; //} } public async Task ExportList(Request request, string fileName, int userId, int companyId, FileDownLoadOrderType type, Mapper mapper = null, int? supplierId = null) where Request : PaginationBaseRequestDto { FileDownManager entity = new FileDownManager(userId, companyId, type, _option.Url + fileName, supplierId); request.PageNo = 1; request.PageSize = _option.PageSize; List> listz = new List>(); string msg = ""; using (var scope = _serviceScopeFactory.CreateScope()) { var _fileDownManagerService = scope.ServiceProvider.GetRequiredService(); entity = await _fileDownManagerService.Add(entity); try { var _service = scope.ServiceProvider.GetRequiredService>(); _logger.LogInformation($"{DateTime.Now}--开始访问数据"); var (obj, total) = await _service.GetListField(request, companyId); var list = (List)obj; var page = Math.Ceiling(Convert.ToDecimal(total) / _option.PageSize); listz.Add(list); for (int i = 1; i < page; i++) { request.PageNo++; var (obj_f, total_f) = await _service.GetListField(request, companyId); var list_f = (List)obj_f; listz.Add(list_f); } _logger.LogInformation($"{DateTime.Now}--访问数据成功 总数:{total}"); } catch (Exception ex) { msg = "未找到数据"; _logger.LogError($"导出数据查询异常 {ex.ToString()}"); } if (listz.Count <= 0) { entity.Finish(false, msg); await _fileDownManagerService.Edit(entity); return; } msg = await Upload(listz, fileName, userId, type); entity.Finish(string.IsNullOrEmpty(msg) == true ? true : false, msg); await _fileDownManagerService.Edit(entity); return; } } private async Task Upload(List> dataList, string fileName, int userId, FileDownLoadOrderType type, Mapper mapper = null) { if (mapper == null) mapper = new Mapper(); //第一个参数为导出Excel名称 //第二个参数为Excel数据来源 //第三个参数为导出的Sheet名称 //overwrite参数如果是要覆盖已存在的Excel或者新建Excel则为true,如果在原有Excel上追加数据则为false //xlsx参数是用于区分导出的数据格式为xlsx还是xls MemoryStream stream = new MemoryStream(); try { for (int i = 0; i < dataList.Count; i++) { mapper.Put(dataList[i], "sheet" + (i + 1), true); } mapper.Save(stream); } catch (Exception) { return "数据导入Execl异常"; } //mapper.Save(stream, dataList, "sheet1", overwrite: true, xlsx: true); //,但是这里也踩到了一个坑,不过这个是 Npoi 的坑并不是 Npoi.Mapper 的坑, // 那就是 Workbook.Write(stream)的时候会将 stream 关闭,如果继续操作这个 Stream 会报流已关闭的错误 //所以这里 是把流先转成byte[] 再转回使用的流 try { var middleByte = stream.ToArray(); using (MemoryStream streamUpload = new MemoryStream(middleByte)) { var res = await _qiniuUploadService.Upload(fileName, streamUpload, true); if (!res.Success) { _logger.LogError($"{DateTime.Now}--上传千牛云失败 原因:{res.Message}"); return res.Message; } } } catch (Exception) { return "数据上传云端异常"; } _logger.LogInformation($"{DateTime.Now}--导出成功"); return ""; } } }