一厂MES,含注塑,喷涂,冲孔
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.2 KiB

3 months ago
using MESWebSite.CommonClass;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
namespace MESWebSite.Tool
{
public class ExcelTool
{
/// <summary>
/// 导出Excel
/// </summary>
/// <typeparam name="T">导出的数据集合类型</typeparam>
/// <param name="data">导出的数据集合</param>
/// <param name="type">导出的Excel实体类型</param>
/// <returns></returns>
public XSSFWorkbook Export<T>(List<T> data, Type type) where T : class
{
XSSFWorkbook book = new XSSFWorkbook();
ISheet sheet = book.CreateSheet("Sheet1");
IRow hrow = sheet.CreateRow(0);
PropertyInfo[] prop = type.GetProperties();
// 通过反射写入表头
WriteHeader(hrow, prop);
// 通国反射写入内容
WriteContent(sheet, data, prop);
return book;
}
public void WriteHeader(IRow row, PropertyInfo[] header)
{
for (int i = 0; i < header.Length; i++)
{
ICell cell = row.CreateCell(i);
var col = header[i];
ExportHeaderAttribute attr = col.GetCustomAttribute<ExportHeaderAttribute>();
if (attr == null)
{
cell.SetCellValue(col.Name);
}
else
{
cell.SetCellValue(attr.HeaderName);
}
}
}
public void WriteContent<T>(ISheet sheet, List<T> data, PropertyInfo[] header)
{
for (int i = 0; i < data.Count; i++)
{
IRow row = sheet.CreateRow(i + 1);
for (int j = 0; j < header.Length; j++)
{
ICell cell = row.CreateCell(j);
T o = data[i];
var prop = o.GetType().GetProperty(header[j].Name);
if (prop != null)
{
cell.SetCellValue(prop.GetValue(o).ToString());
}
}
}
}
}
}