You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

326 lines
11 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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);
// 释放资源
//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)
// {
// 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; }
}
}