修改Excel导出

dev
jianghaiqing 4 weeks ago
parent 7282e783cd
commit 8b658a8b6c

@ -220,6 +220,16 @@ namespace DS.WMS.Core.TaskPlat.Dtos
/// 箱信息列表
/// </summary>
public List<TaskMessageCtnInfo> ContaList { get; set; }
/// <summary>
/// 网站的账户(网站需要登录的需要提供)
/// </summary>
public string WebUser { get; set; }
/// <summary>
/// 网站的密码(网站需要登录的需要提供)
/// </summary>
public string WebPassword { get; set; }
}
/// <summary>

@ -5,6 +5,7 @@ using DS.Module.Core.Helpers;
using DS.Module.DjyServiceStatus;
using DS.Module.SqlSugar;
using DS.Module.UserModule;
using DS.WMS.Core.Code.Dtos;
using DS.WMS.Core.Code.Interface;
using DS.WMS.Core.Code.Method;
using DS.WMS.Core.Invoice.Dtos;
@ -12,6 +13,8 @@ using DS.WMS.Core.Map.Interface;
using DS.WMS.Core.Map.Method;
using DS.WMS.Core.Op.Dtos;
using DS.WMS.Core.Op.Entity;
using DS.WMS.Core.Sys.Interface;
using DS.WMS.Core.Sys.Method;
using DS.WMS.Core.TaskPlat.Dtos;
using DS.WMS.Core.TaskPlat.Entity;
using DS.WMS.Core.TaskPlat.Interface;
@ -47,6 +50,8 @@ namespace DS.WMS.Core.TaskPlat.Method
private readonly IMappingYardService _mappingYardService;
private readonly IMappingCarrierService _mappingCarrierService;
private readonly ICodePortService _codePortService;
private readonly ICodeThirdPartyService _codeThirdPartyService;
private readonly IConfigService _configService;
private readonly string shippingOrderCompareUrl;
private readonly string shippingOrderCompareResultUrl;
@ -66,6 +71,8 @@ namespace DS.WMS.Core.TaskPlat.Method
_mappingYardService = _serviceProvider.GetRequiredService<IMappingYardService>();
_mappingCarrierService = _serviceProvider.GetRequiredService<IMappingCarrierService>();
_codePortService = _serviceProvider.GetRequiredService<ICodePortService>();
_codeThirdPartyService = _serviceProvider.GetRequiredService<ICodeThirdPartyService>();
_configService = _serviceProvider.GetRequiredService<IConfigService>();
shippingOrderCompareUrl = AppSetting.app(new string[] { "ShippingOrderCompare", "Url" });
shippingOrderCompareResultUrl = AppSetting.app(new string[] { "ShippingOrderCompare", "ResultUrl" });
@ -196,6 +203,50 @@ namespace DS.WMS.Core.TaskPlat.Method
mainInfo.ContaList = contaList.Adapt<List<TaskMessageCtnInfo>>();
}
CodeThirdPartyRes webAccountConfig = null;
bool isYGT = false;
bool isLuHai = false;
var cfgYGT = _configService.GetConfig("ShipCompareAccountYGT", long.Parse(user.TenantId), false).GetAwaiter().GetResult()?.Data?.Value;
if (!string.IsNullOrWhiteSpace(cfgYGT))
{
var currArg = cfgYGT.Split(new char[] { ',' }).ToArray();
if (currArg.Contains(mainInfo.YardCode))
{
isYGT = true;
webAccountConfig = _codeThirdPartyService.GetCodeThirdPartyInfoWithCompany("yungangtong").GetAwaiter().GetResult()?.Data;
}
}
//如果不是云港通,就试试陆海通
if (!isYGT)
{
var cfgLuht = _configService.GetConfig("ShipCompareAccountLUHAI", long.Parse(user.TenantId), false).GetAwaiter().GetResult()?.Data?.Value;
if (!string.IsNullOrWhiteSpace(cfgLuht))
{
var currArg = cfgLuht.Split(new char[] { ',' }).ToArray();
if (currArg.Contains(mainInfo.YardCode))
{
isYGT = true;
webAccountConfig = _codeThirdPartyService.GetCodeThirdPartyInfoWithCompany("LuHaiTong").GetAwaiter().GetResult()?.Data;
}
}
}
if (webAccountConfig != null)
{
mainInfo.WebUser = webAccountConfig.AppKey;
mainInfo.WebPassword = webAccountConfig.AppSecret;
}
var msgModel = GetMessageInfo(batchNo, mainInfo);
Logger.Log(NLog.LogLevel.Info, "批次={no} 对应请求报文完成 msg={msg}", batchNo, JsonConvert.SerializeObject(msgModel));

@ -1,283 +1,325 @@
using LanguageExt;
using iText.Kernel.Utils.Objectpathitems;
using iText.Kernel.XMP.Impl.XPath;
using LanguageExt;
using LanguageExt.TypeClasses;
using Masuit.Tools.Strings;
using Microsoft.AspNetCore.Identity;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using static iText.StyledXmlParser.Jsoup.Select.Evaluator;
namespace DS.WMS.Core.Utils
{
public class ExportFileHelper
{
/// <summary>
/// Excel行高Height的单位是1/20个点。例设置高度为25个点
/// </summary>
private static short rowHeight = 25 * 20;
#region 导出Excel
#region 导出
/// <summary>
/// 导出
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="strHeader">列名</param>
/// <param name="fileName">绝对路径</param>
/// <param name="sheetName">sheet页名</param>
public static void Export<T>(List<T> dataList, Dictionary<string, string> colDicts, string fileName, string sheetName = "Sheet1")
{
// 使用 NPOI 组件导出 Excel 文件
//XSSFWorkbook:是操作Excel2007的版本扩展名是.xlsx
XSSFWorkbook workbook = new XSSFWorkbook();
//HSSFWorkbook:是操作Excel2003以前包括2003的版本扩展名是.xls
//HSSFWorkbook workbook = new HSSFWorkbook();
//创建Sheet
ISheet sheet = workbook.CreateSheet(sheetName);
//设置单元格样式
ICellStyle style = SetCellStyle(workbook);
//创建表格
NPOICreateTable(dataList, colDicts, sheet, style, 0);
// 将 Excel 文件保存到磁盘
NPOISaveFile(workbook, fileName);
// 释放资源
//workbook.Dispose();
}
#endregion
#region 自定义框架,导出
/// <summary>
/// 自定义顶部,导出
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="strArry">拆分后列名</param>
/// <param name="fileName">绝对路径,路径+文件名+后缀</param>
/// <param name="num">新一行索引,开始</param>
/// <param name="workbook"></param>
/// <param name="sheet"></param>
public static void Export<T>(List<T> dataList, Dictionary<string, string> colDicts, string fileName, int num, XSSFWorkbook workbook, ISheet sheet)
{
//设置单元格样式
ICellStyle style = SetCellStyle(workbook);
//创建表格
NPOICreateTable(dataList, colDicts, sheet, style, num);
// 将 Excel 文件保存到磁盘
NPOISaveFile(workbook, fileName);
// /// <summary>
// /// 导出
// /// </summary>
// /// <typeparam name="T"></typeparam>
// /// <param name="list"></param>
// /// <param name="colDicts"></param>
// /// <returns></returns>
// public async Task<string> Export<T>(List<T> dataLiist, Dictionary<string,string> colDicts)
// 释放资源
//workbook.Dispose();
}
#endregion
#endregion
#region 获取用户选择保存路径
/// <summary>
/// 获取让用户选择保存文件的绝对路径
/// </summary>
/// <returns></returns>
//public static string GetSaveFileRoute(string filter, string fileName)
//{
// SaveFileDialog dialog = new SaveFileDialog();
// dialog.Filter = filter;
// dialog.FileName = fileName;
// if (dialog.ShowDialog() == true)
// {
// string filePath = string.Empty;
// /*
// 1、生成空Excel文件。
// 2、根据colDicts提供的key来匹配字段列表的
// 3、暂存文件并返回完整文件名
// */
// try
// {
// string sheetName = "";
// XSSFWorkbook workbook = new XSSFWorkbook();
// ISheet sheet = workbook.CreateSheet(sheetName);
// #region Excel模板打印
// //var opt = App.GetOptions<PrintTemplateOptions>();
// //var dirAbs = opt.basePath;
// //if (string.IsNullOrEmpty(dirAbs))
// //{
// // dirAbs = App.WebHostEnvironment.WebRootPath;
// //}
// var fileAbsPath = Path.Combine(dirAbs, printTemplate.FilePath);
// //_logger.LogInformation($"准备调用EXCEL生成id{id},文件:{printTemplate.FileName}");
// var result = new FileStream(fileAbsPath, FileMode.Open);
// var excelwork = new HSSFWorkbook(result);
// var sheet = excelwork.GetSheetAt(0);
// var entity = await _bookingExcelTemplateRepository.AsQueryable()
// .Where(x => x.PId == templateId).OrderBy(x => x.Row).ToListAsync();
// if (entity == null)
// {
// throw Oops.Bah("当前模板未设置");
// }
// for (int _row = 1; _row <= entity.Max(x => x.Row); _row++)
// {
// if (entity.Where(x => x.Row == _row).Count() > 0)
// {
// ////获取行
// var row = sheet.GetRow(_row - 1);
// if (row != null)
// {
// for (int _cellNum = 1; _cellNum <= entity.Max(x => x.Column); _cellNum++)
// {
// if (entity.Where(x => x.Row == _row && x.Column == _cellNum).Count() > 0)
// {
// var name = entity.Where(x => x.Row == _row && x.Column == _cellNum).Select(x => x.Field).FirstOrDefault();
// if (name.Split('.')[0].ToLower() == "order")
// {
// foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(order))
// {
// var _name = descriptor.Name.ToLower();
// if (name.Split('.')[0].ToLower() == "order" && name.Split('.')[1].ToLower() == _name)
// {
// var value = descriptor.GetValue(order) != null ? descriptor.GetValue(order).ToString() : "";
// ICell cell = row.GetCell(_cellNum - 1);
// if (descriptor.PropertyType.FullName.Contains("DateTime"))
// {
// value = value != "" ? Convert.ToDateTime(value).ToString("yyyy-MM-dd") : "";
// }
// if (cell != null)
// {
// row.Cells[_cellNum - 1].SetCellValue(value);
// }
// else
// {
// row.CreateCell(_cellNum - 1).SetCellValue(value);
// }
// }
// }
// }
// if (name.Split('.')[0].ToLower() == "edi")
// {
// foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(edi))
// {
// var _name = descriptor.Name.ToLower();
// if (name.Split('.')[0].ToLower() == "edi" && name.Split('.')[1].ToLower() == _name)
// {
// var value = descriptor.GetValue(edi) != null ? descriptor.GetValue(edi).ToString() : "";
// ICell cell = row.GetCell(_cellNum - 1);
// if (descriptor.PropertyType.FullName.Contains("DateTime"))
// {
// value = value != "" ? Convert.ToDateTime(value).ToString("yyyy-MM-dd") : "";
// }
// if (cell != null)
// {
// row.Cells[_cellNum - 1].SetCellValue(value);
// }
// else
// {
// row.CreateCell(_cellNum - 1).SetCellValue(value);
// }
// }
// }
// }
// if (name.Split('.')[0].ToLower() == "userinfo")
// {
// ICell cell = row.GetCell(_cellNum - 1);
// var value = string.Empty;
// if (name.Split('.')[1].ToLower() == "username")
// {
// value = UserManager.Name;
// }
// if (name.Split('.')[1].ToLower() == "usertel")
// {
// value = UserManager.TEl;
// }
// if (name.Split('.')[1].ToLower() == "usermobile")
// {
// value = UserManager.Phone;
// }
// if (name.Split('.')[1].ToLower() == "useremail")
// {
// value = UserManager.Email;
// }
// if (name.Split('.')[1].ToLower() == "usertenant")
// {
// value = UserManager.TENANT_NAME;
// }
// if (cell != null)
// {
// row.Cells[_cellNum - 1].SetCellValue(value);
// }
// else
// {
// row.CreateCell(_cellNum - 1).SetCellValue(value);
// }
// }
// }
// }
// }
// else
// {
// ////创建行
// var srow = NpoiExcelExportHelper._.CreateRow(sheet, _row - 1);
// for (int _cellNum = 1; _cellNum <= entity.Max(x => x.Column); _cellNum++)
// {
// if (entity.Where(x => x.Row == _row && x.Column == _cellNum).Count() > 0)
// {
// var name = entity.Where(x => x.Row == _row && x.Column == _cellNum).Select(x => x.Field).FirstOrDefault();
// if (name.Split('.')[0].ToLower() == "order")
// {
// foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(order))
// {
// var _name = descriptor.Name.ToLower();
// if (name.Split('.')[1].ToLower() == _name && name.Split('.')[0].ToLower() == "order")
// {
// var value = descriptor.GetValue(order) != null ? descriptor.GetValue(order).ToString() : "";
// if (descriptor.PropertyType.FullName.Contains("DateTime"))
// {
// value = value != "" ? Convert.ToDateTime(value).ToString("yyyy-MM-dd") : "";
// }
// srow.CreateCell(_cellNum - 1).SetCellValue(value);
// }
// }
// }
// if (name.Split('.')[0].ToLower() == "edi")
// {
// foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(edi))
// {
// var _name = descriptor.Name.ToLower();
// if (name.Split('.')[1].ToLower() == _name && name.Split('.')[0].ToLower() == "edi")
// {
// var value = descriptor.GetValue(edi) != null ? descriptor.GetValue(edi).ToString() : "";
// if (descriptor.PropertyType.FullName.Contains("DateTime"))
// {
// value = value != "" ? Convert.ToDateTime(value).ToString("yyyy-MM-dd") : "";
// }
// srow.CreateCell(_cellNum - 1).SetCellValue(value);
// }
// }
// }
// if (name.Split('.')[0].ToLower() == "userinfo")
// {
// var value = string.Empty;
// if (name.Split('.')[1].ToLower() == "username")
// {
// value = UserManager.Name;
// }
// if (name.Split('.')[1].ToLower() == "usertel")
// {
// value = UserManager.TEl;
// }
// if (name.Split('.')[1].ToLower() == "usermobile")
// {
// value = UserManager.Phone;
// }
// if (name.Split('.')[1].ToLower() == "useremail")
// {
// value = UserManager.Email;
// }
// if (name.Split('.')[1].ToLower() == "usertenant")
// {
// value = UserManager.TENANT_NAME;
// }
// srow.CreateCell(_cellNum - 1).SetCellValue(value);
// }
// }
// }
// }
// }
// }
// var fileFullPath = Path.Combine(App.WebHostEnvironment.WebRootPath, App.GetOptions<TempFileOptions>().Path);//服务器路径
// if (!Directory.Exists(fileFullPath))
// {
// Directory.CreateDirectory(fileFullPath);
// }
// fileName = $"{DateTime.Now.Ticks}.xls";//名称
// ////2023-4-3根据河川操作要求文件名只带提单号
// //if (!string.IsNullOrEmpty(order.MBLNO))
// //{
// // fileName = $"{order.MBLNO}.xls";//名称
// //}
// //else
// //{
// // fileName = $"{order.Id}_{DateTime.Now.Ticks}.xls";//名称
// //}
// _logger.LogInformation("导出excel:" + Path.Combine(fileFullPath, fileName));
// var filestream = new FileStream(Path.Combine(fileFullPath, fileName), FileMode.OpenOrCreate, FileAccess.ReadWrite);
// excelwork.Write(filestream);
// #endregion
// }
// catch (Exception ex)
// {
// }
// return filePath;
// return dialog.FileName;
// }
// return "";
//}
#endregion
#region 保存文件
private static string NPOISaveFile(XSSFWorkbook workbook, string fileName)
{
try
{
// 将 Excel 文件保存到磁盘
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
return "";
}
catch (Exception err)
{
return err.Message;
}
}
#endregion
#region 创建表格
/// <summary>
/// 创建表格
/// </summary>
/// <param name="dataList">数据源</param>
/// <param name="strArry">拆分后的列名</param>
/// <param name="sheet">Sheet页</param>
/// <param name="style">样式</param>
/// <param name="num">行索引</param>
private static void NPOICreateTable<T>(List<T> dataList, Dictionary<string, string> colDicts, ISheet sheet, ICellStyle style, int num)
{
string[] strArry = colDicts.Select(b => b.Value).ToArray();
IRow row = null;//声明行
#region 创建列名
//在索引 num 的位置 创建一行
row = sheet.CreateRow(num);
row.Height = rowHeight;//设置行高
//循环列名数组,创建单元格并赋值、样式
for (int i = 0; i < strArry.Length; i++)
{
row.CreateCell(i).SetCellValue(strArry[i]);
row.GetCell(i).CellStyle = style;
}
#endregion
#region 创建行
//循环数据源 创建行
for (int i = 0; i < dataList.Count; i++)
{
//创建行
row = sheet.CreateRow(num + 1);
row.Height = rowHeight;//设置行高
num++;//行索引自增
Dictionary<string, Tuple<string, string>> dataDict = new Dictionary<string, Tuple<string, string>>();
foreach (System.Reflection.PropertyInfo p in dataList[i].GetType().GetProperties())
{
var value = p.GetValue(dataList[i]);
dataDict.Add(p.Name,new Tuple<string, string>(value.ToString(), p.PropertyType.Name));
}
//循环数据源列集合,创建单元格
foreach (var col in colDicts)
{
//var pList = TypeDescriptor.GetProperties(T)
string ValueType = "";//值类型
string Value = "";//值
//类型 和 值,赋值
//if (dt.Rows[i][j].ToString() != null)
//{
// ValueType = dt.Rows[i][j].GetType().ToString();
// Value = dt.Rows[i][j].ToString();
//}
var j = 0;
//根据不同数据类型,对数据处理。处理后创建单元格并赋值 和 样式
switch (ValueType)
{
case "System.String"://字符串类型
row.CreateCell(j).SetCellValue(Value);
break;
case "System.DateTime"://日期类型
System.DateTime dateV;
System.DateTime.TryParse(Value, out dateV);
row.CreateCell(j).SetCellValue(dateV.ToString("yyyy-MM-dd"));
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(Value, out boolV);
row.CreateCell(j).SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(Value, out intV);
row.CreateCell(j).SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
double.TryParse(Value, out doubV);
row.CreateCell(j).SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
row.CreateCell(j).SetCellValue("");
break;
default:
row.CreateCell(j).SetCellValue("");
break;
}
row.GetCell(j).CellStyle = style;
//设置宽度
//sheet.SetColumnWidth(j, (Value.Length + 10) * 256);
}
}
#endregion
//循环列名数组,多所有列 设置 自动列宽
for (int i = 0; i < strArry.Length; i++)
{
sheet.AutoSizeColumn(i);
}
}
#endregion
public string GetPropertyValue<T>(T t, string field)
{
string value = "9";
if (t == null)
{
return value;
}
PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
if (properties.Length <= 0)
{
return value;
}
var property = properties.Where(x => x.Name == field).FirstOrDefault();
value = property.GetValue(t, null).ToString();
return value;
}
#region 设置单元格样式
public static ICellStyle SetCellStyle(XSSFWorkbook workbook)
{
#region 单元格样式
//创建一个样式
ICellStyle style = workbook.CreateCellStyle();
style.Alignment = HorizontalAlignment.Center;//水平对齐
style.VerticalAlignment = VerticalAlignment.Center;//垂直对齐
style.BorderBottom = BorderStyle.Thin;//下边框为细线边框
style.BorderLeft = BorderStyle.Thin;//左边框
style.BorderRight = BorderStyle.Thin;//上边框
style.BorderTop = BorderStyle.Thin;//右边框
#endregion
return style;
}
#endregion
}
/// <summary>
/// 导出excel-中英文规则类
/// </summary>
public class ExportRegular
{
/// <summary>
/// 属性名称(英文)
/// </summary>
public string PropertyName { get; set; }
/// <summary>
/// 数据类型
/// </summary>
public string DataType { get; set; }
/// <summary>
/// 导出名称(中文)
/// </summary>
public string ExportFieldName { get; set; }
}
}

@ -12,6 +12,7 @@ using DS.WMS.Core.Op.EDI;
using DS.WMS.Core.Op.Interface;
using DS.WMS.Core.Sys.Dtos;
using DS.WMS.Core.Sys.Interface;
using DS.WMS.Core.Utils;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NPOI.XWPF.UserModel;
@ -566,4 +567,30 @@ public class SeaExportController : ApiController
return res;
}
/// <summary>
/// 导出
/// </summary>
/// <param name="id">业务Id</param>
/// <returns></returns>
[HttpGet]
[Route("ExportOrder")]
public async Task<DataResult<string>> ExportOrder([FromQuery] long id)
{
List<SeaExportRes> list = new List<SeaExportRes> {
new SeaExportRes{
Id = 1,
MBLNO = "TEST",
}
};
Dictionary<string, string> colDicts = new Dictionary<string, string> {
{ "Id","主键"}, { "MBLNO","提单号"}
};
ExportFileHelper.Export<SeaExportRes>(list, colDicts, "text");
return DataResult<string>.Success("");
}
}
Loading…
Cancel
Save