C#导出Excel表格方法

时间:2022-01-11 21:30:26
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Formula.Functions;
using System.Reflection;
using System.IO; public class Exportmethod
{
/// <summary>
/// 导出Excel表格
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="listEntity"></param>
/// <returns></returns>
public static byte[] Output<T>(List<T> listEntity) where T : class
{
Type entityType = (listEntity?.FirstOrDefault()).GetType();
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet("sheet");
var scd = typeof(System.ComponentModel.DisplayNameAttribute);
var entityProperties = entityType.GetProperties().Where(item => item.GetCustomAttribute(scd) != null).ToList();
IRow Title = sheet.CreateRow();
IRow rows = null;         
for (int i = ; i < listEntity.Count; i++)
{
var dbitem = listEntity[i];
rows = sheet.CreateRow(i+);
for (int j = ; j < entityProperties.Count; j++)
{
var prop = entityProperties[j];
if (i == )
{
              //表头赋值
var display = prop.GetCustomAttribute(scd) as System.ComponentModel.DisplayNameAttribute;
Title.CreateCell(j).SetCellValue(display.DisplayName); }
            //表格数据
var value = prop.GetValue(dbitem)?.ToString();
rows.CreateCell(j).SetCellValue(value ?? "");
}
} using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
return ms.GetBuffer();
}
}

下面是实体模型,需要在前面加DisplayName,这样做的意义是有多少就生成多少列

 /// <summary>
/// 视图模型
/// </summary>
public class QueryListDataDto
{
/// <summary>
/// ID
/// </summary>
[DisplayName("编号")]
public int Id { get; set; } /// <summary>
/// 名称
/// </summary>
[DisplayName("名称")]
public string Name { get; set; } /// <summary>
/// 说明
/// </summary>
[DisplayName("说明")]
public string Description { get; set; }

条件:需要NPOI包