Remarks:
The controller created by the Demo project is the .NET Core3.1 framework
1. Console application code
using System;
using System.Collections.Generic;
using System.IO;
namespace Excel_Export
{
class Program
{
static void Main(string[] args)
{
var list = new List<TestExcel>() {
new TestExcel(){
Name="张三",Address="福建"},
new TestExcel(){
Name="李四",Address="厦门"},
new TestExcel(){
Name="王五",Address="泉州"},
};
Console.WriteLine("开始执行");
var bytes = ExcelConvert.ToExcelBytes(list);
var path = Path.Combine(AppContext.BaseDirectory, "temporary", "excel");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var savePath = Path.Combine(path, "TestExport.xls");
Console.WriteLine($"保存路径:{savePath}");
using (FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write))
{
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
}
Console.WriteLine("执行结束");
Console.ReadLine();
}
}
/// <summary>
/// 测试Excel模型
/// </summary>
public class TestExcel
{
/// <summary>
/// 姓名
/// </summary>
[ExcelColumn("姓名")]
public string Name {
get; set; }
/// <summary>
/// 分组
/// </summary>
[ExcelColumn("地址")]
public string Address {
get; set; }
}
}
2. Help class code
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Excel_Export
{
/// <summary>
/// Excel帮助类
/// </summary>
public class ExcelConvert
{
public static byte[] ToExcelBytes<TEntity>(IList<TEntity> items) where TEntity : class, new()
{
var workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("sheet1");
SetTitle<TEntity>(workbook, sheet);
int index = 1;
foreach (TEntity entity in items)
{
IRow row = sheet.CreateRow(index);
PropertyInfo[] values = entity.GetType().GetProperties();
int col = 0;
foreach (PropertyInfo property in values)
{
object val = property.GetValue(entity, null);
if (val == null)
row.CreateCell(col).SetCellValue("");
else
row.CreateCell(col).SetCellValue(val.ToString());
col++;
}
index++;
}
//写入
using (var file = new MemoryStream())
{
workbook.Write(file);
return file.GetBuffer();
}
}
private static void SetTitle<T>(HSSFWorkbook workbook, ISheet sheet)
{
var titles = new List<string>();
PropertyInfo[] propertys = typeof(T).GetProperties();
foreach (PropertyInfo property in propertys)
{
object[] excelColumns = property.GetCustomAttributes(typeof(ExcelColumnAttribute), true);
if (excelColumns.Length > 0)
{
string like = (excelColumns[0] as ExcelColumnAttribute).DisplayNameLike;
if (!string.IsNullOrEmpty(like))
{
titles.Add(like);
}
else
{
titles.Add(property.Name);
}
}
}
//写入
IRow row = sheet.CreateRow(0);
for (int i = 0; i < titles.Count; i++)
{
row.CreateCell(i).SetCellValue(titles[i]);
}
}
private class EntityColumn
{
public string ColumnName {
get; set; }
public int ExcelIndex {
get; set; }
}
}
/// <summary>
/// Excel列属性【添加标签对象】
/// </summary>
public class ExcelColumnAttribute : Attribute
{
public ExcelColumnAttribute()
{
ExcelIndex = -1;
}
public ExcelColumnAttribute(int excelIndex)
{
ExcelIndex = excelIndex;
}
public ExcelColumnAttribute(string displayNameLike)
{
DisplayNameLike = displayNameLike;
}
public int ExcelIndex {
get; set; }
public string DisplayNameLike {
get; set; }
}
}
result:
Remarks:
Reference for implementing the function of merging rows - merging Excel cells