using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Weixiao.Common
{
[AttributeUsage(AttributeTargets.All)]
public class NpoiAttribute : Attribute
{
/// <summary>
/// 文件名称
/// </summary>
public string FileName { get; set; }
/// <summary>
/// 文件路径
/// </summary>
public string FilePath { get; set; }
/// <summary>
/// 文件后缀(.xls/.xlsx)
/// </summary>
public string FileSuffix { get; set; }
/// <summary>
/// 工作本
/// </summary>
public string SheetName { get; set; }
public NpoiAttribute(string fileName, string filePath, string sheetName, string fileSuffix)
{
FileName = fileName;
FilePath = filePath;
SheetName = sheetName;
FileSuffix = fileSuffix;
}
public NpoiAttribute(string fileName, string filePath, string sheetName)
{
FileName = fileName;
FilePath = filePath;
SheetName = sheetName;
FileSuffix = ".xlsx";
}
public NpoiAttribute()
{
}
}
[AttributeUsage(AttributeTargets.All)]
public class NpoiRowAttribute : Attribute
{
/// <summary>
/// 表头
/// </summary>
public string TabTitle { get; set; }
public NpoiRowAttribute(string tabTitle)
{
TabTitle = tabTitle;
}
public NpoiRowAttribute()
{
}
}
public class NpoiUtil
{
/// <summary>
/// excel导出(配合NpoiAttribute)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataList">数据源</param>
/// <param name="filePath">文件路径</param>
/// <param name="fileName">文件名称</param>
public static string CreateByAttribute<T>(List<T> dataList,string rootPath, string filePath = null, string fileName = null)
{
var tp = typeof(T);
NpoiAttribute npoiAttr = new NpoiAttribute();
foreach (System.Attribute a in tp.GetCustomAttributes(true))
{
if (a is NpoiAttribute)
{
npoiAttr = (NpoiAttribute)a;
}
}
IWorkbook workbook;
if (npoiAttr.FileSuffix == ".xls") workbook = new HSSFWorkbook();
else workbook = new XSSFWorkbook();
var sheet = workbook.CreateSheet(npoiAttr.SheetName);
var titleCellIndex = 0;//表头列数
var rowIndex = 0;//行数
var titleRow = sheet.CreateRow(rowIndex);
rowIndex++;
// 冻结第一行
sheet.CreateFreezePane(0, 1, 0, 1);
var titleDic = new Dictionary<string, int>();
foreach (var pro in tp.GetProperties())
{
if (pro.PropertyType.Namespace != "System")
{//非基础变量暂不支持
continue;
}
//var x = pro.PropertyType.Name.ToLower();
//var intoTypeList = new string[] { "int32", "int64", "int", "bool", "decimal", "string", "nullable`1" };
//if (intoTypeList.FirstOrDefault(d=>d.ToLower()==pro.PropertyType.Name.ToLower()) is null)
//{
// continue;
//}
titleDic.Add(pro.Name, titleCellIndex);
var tabTitle = pro.Name;
foreach (Attribute fa in pro.GetCustomAttributes(true))
{
if (fa is NpoiRowAttribute)
{
var faa = (NpoiRowAttribute)fa;
tabTitle = faa.TabTitle;
break;
}
}
titleRow.CreateCell(titleCellIndex).SetCellValue(tabTitle);
titleCellIndex++;
}
foreach (var item in dataList)
{
var dataRow = sheet.CreateRow(rowIndex);
rowIndex++;
foreach (var p in tp.GetProperties())
{
var td = titleDic.FirstOrDefault(t => t.Key == p.Name);
if (string.IsNullOrEmpty(td.Key))
{
continue;
}
dataRow.CreateCell(td.Value).SetCellValue(p.GetValue((T)item) == null ? "" : p.GetValue((T)item).ToString());
}
}
npoiAttr.FilePath = string.IsNullOrEmpty(filePath) ? npoiAttr.FilePath : filePath;
npoiAttr.FileName = string.IsNullOrEmpty(fileName) ? npoiAttr.FileName : fileName;
//if (!Directory.Exists(npoiAttr.FilePath)) Directory.CreateDirectory(npoiAttr.FilePath);
//todo:抽空检查下,为啥没有在wwwroot下
if (!Directory.Exists(Path.Combine(rootPath,npoiAttr.FilePath))) {
Directory.CreateDirectory(Path.Combine(rootPath, npoiAttr.FilePath));
}
// var path1 = Directory.GetCurrentDirectory();
var path = Path.Combine(npoiAttr.FilePath ?? "upload", $"{npoiAttr.FileName ?? "数据"}{npoiAttr.FileSuffix ?? ".xlsx"}");
FileStream sw = File.Create(Path.Combine(rootPath,path));
workbook.Write(sw);
sw.Close();
return path;
}
public static void Create(WoorkBook work)
{
IWorkbook workbook;
if (work.Suffix.ToLower() == ".xls") workbook = new HSSFWorkbook();
else workbook = new XSSFWorkbook();
foreach (var sheet in work.Sheets)
{
var _sheet = workbook.CreateSheet(sheet.Name);
var rowIndex = 0;
if (sheet.Title != null)
{//表示有标题
var row = _sheet.CreateRow(rowIndex);
for (int i = 0; i < sheet.Title.Count; i++)
{
row.CreateCell(i).SetCellValue(sheet.Title[i]);
}
rowIndex++;
}
for (int i = rowIndex; i < sheet.Value.Count; i++)
{//内容
var rowValue = _sheet.CreateRow(i);
for (int j = 0; j < sheet.Value[i].Count; j++)
{
rowValue.CreateCell(j).SetCellValue(sheet.Value[i][j].ToString());
}
}
}
}
}
public class WoorkBook
{
/// <summary>
/// 文件名称(别写后缀了)
/// </summary>
public string Name { get; set; }
/// <summary>
/// 文件路径
/// </summary>
public string Path { get; set; }
/// <summary>
/// 文件后缀".xls"或者“.xlsx”
/// </summary>
public string Suffix { get; set; }
public List<Sheet> Sheets { get; set; }
}
public class Sheet
{
/// <summary>
/// 工作单元名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 标题
/// </summary>
public List<string> Title { get; set; }
/// <summary>
/// 值
/// </summary>
public List<List<object>> Value { get; set; }
}
}
c# npoi下载导出excel(奇思妙想通过字段属性和反射处理)
最新推荐文章于 2024-04-27 16:35:29 发布