using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; // 处理.xlsx格式
using NPOI.HSSF.UserModel; // 处理.xls格式
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
public class ExcelExporter<T> where T : class
{
/// <summary>
/// 导出泛型List到Excel文件
/// </summary>
/// <param name="data">数据列表</param>
/// <param name="filePath">保存路径,支持.xls和.xlsx</param>
/// <param name="sheetName">工作表名称</param>
/// <param name="includeHeader">是否包含表头</param>
/// <param name="propertyNames">指定导出的属性名(可选,默认导出所有公共属性)</param>
public void Export(List<T> data, string filePath, string sheetName = "Sheet1", bool includeHeader = true, List<string> propertyNames = null)
{
if (data == null || data.Count == 0)
throw new ArgumentException("导出数据不能为空");
if (string.IsNullOrEmpty(filePath))
throw new ArgumentNullException(nameof(filePath));
IWorkbook workbook;
string ext = Path.GetExtension(filePath).ToLower();
if (ext == ".xls")
{
workbook = new HSSFWorkbook();
}
else if (ext == ".xlsx")
{
workbook = new XSSFWorkbook();
}
else
{
throw new ArgumentException("文件扩展名必须是 .xls 或 .xlsx");
}
ISheet sheet = workbook.CreateSheet(sheetName);
// 通过反射获取属性列表
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
// 如果指定了导出属性,则过滤
if (propertyNames != null && propertyNames.Count > 0)
{
props = props.Where(p => propertyNames.Contains(p.Name)).ToArray();
}
int rowIndex = 0;
// 写表头
if (includeHeader)
{
IRow headerRow = sheet.CreateRow(rowIndex++);
for (int i = 0; i < props.Length; i++)
{
ICell cell = headerRow.CreateCell(i);
cell.SetCellValue(props[i].Name);
// 设置加粗样式
ICellStyle style = workbook.CreateCellStyle();
IFont font = workbook.CreateFont();
font.IsBold = true;
style.SetFont(font);
cell.CellStyle = style;
}
}
// 写数据
foreach (var item in data)
{
IRow row = sheet.CreateRow(rowIndex++);
for (int i = 0; i < props.Length; i++)
{
ICell cell = row.CreateCell(i);
object value = props[i].GetValue(item);
SetCellValue(cell, value);
}
}
// 自动列宽
for (int i = 0; i < props.Length; i++)
{
sheet.AutoSizeColumn(i);
}
// 保存文件
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
}
/// <summary>
/// 根据数据类型设置单元格值
/// </summary>
private void SetCellValue(ICell cell, object value)
{
if (value == null)
{
cell.SetCellValue(string.Empty);
return;
}
switch (Type.GetTypeCode(value.GetType()))
{
case TypeCode.Boolean:
cell.SetCellValue((bool)value);
break;
case TypeCode.DateTime:
cell.SetCellValue((DateTime)value);
ICellStyle dateStyle = cell.Sheet.Workbook.CreateCellStyle();
short dateFormat = cell.Sheet.Workbook.CreateDataFormat().GetFormat("yyyy-mm-dd HH:mm:ss");
dateStyle.DataFormat = dateFormat;
cell.CellStyle = dateStyle;
break;
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.Single:
cell.SetCellValue(Convert.ToDouble(value));
break;
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
cell.SetCellValue(Convert.ToInt64(value));
break;
default:
cell.SetCellValue(value.ToString());
break;
}
}
}
使用示例
csharp
using System;
using System.Collections.Generic;
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthday { get; set; }
public bool IsActive { get; set; }
}
class Program
{
static void Main()
{
List<User> users = new List<User>()
{
new User { Id = 1, Name = "张三", Birthday = new DateTime(1990, 1, 1), IsActive = true },
new User { Id = 2, Name = "李四", Birthday = new DateTime(1985, 5, 23), IsActive = false }
};
ExcelExporter<User> exporter = new ExcelExporter<User>();
exporter.Export(users, "users.xlsx", "用户列表");
Console.WriteLine("导出完成!");
}
}
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
public static class ExcelExportHelper
{
/// <summary>
/// 导出泛型List到Excel内存流
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">数据列表</param>
/// <param name="sheetName">工作表名称</param>
/// <param name="includeHeader">是否包含表头</param>
/// <param name="propertyNames">指定导出的属性名(可选)</param>
/// <param name="isXlsx">是否导出xlsx格式,false导出xls</param>
/// <returns>Excel文件的内存流</returns>
public static MemoryStream ExportToExcelStream<T>(List<T> data, string sheetName = "Sheet1", bool includeHeader = true, List<string> propertyNames = null, bool isXlsx = true) where T : class
{
if (data == null || data.Count == 0)
throw new ArgumentException("导出数据不能为空");
IWorkbook workbook = isXlsx ? (IWorkbook)new XSSFWorkbook() : new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet(sheetName);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
if (propertyNames != null && propertyNames.Count > 0)
{
props = props.Where(p => propertyNames.Contains(p.Name)).ToArray();
}
int rowIndex = 0;
if (includeHeader)
{
IRow headerRow = sheet.CreateRow(rowIndex++);
for (int i = 0; i < props.Length; i++)
{
ICell cell = headerRow.CreateCell(i);
cell.SetCellValue(props[i].Name);
ICellStyle style = workbook.CreateCellStyle();
IFont font = workbook.CreateFont();
font.IsBold = true;
style.SetFont(font);
cell.CellStyle = style;
}
}
foreach (var item in data)
{
IRow row = sheet.CreateRow(rowIndex++);
for (int i = 0; i < props.Length; i++)
{
ICell cell = row.CreateCell(i);
object value = props[i].GetValue(item);
SetCellValue(cell, value);
}
}
for (int i = 0; i < props.Length; i++)
{
sheet.AutoSizeColumn(i);
}
var ms = new MemoryStream();
workbook.Write(ms);
ms.Position = 0;
return ms;
}
private static void SetCellValue(ICell cell, object value)
{
if (value == null)
{
cell.SetCellValue(string.Empty);
return;
}
switch (Type.GetTypeCode(value.GetType()))
{
case TypeCode.Boolean:
cell.SetCellValue((bool)value);
break;
case TypeCode.DateTime:
cell.SetCellValue((DateTime)value);
ICellStyle dateStyle = cell.Sheet.Workbook.CreateCellStyle();
short dateFormat = cell.Sheet.Workbook.CreateDataFormat().GetFormat("yyyy-MM-dd HH:mm:ss");
dateStyle.DataFormat = dateFormat;
cell.CellStyle = dateStyle;
break;
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.Single:
cell.SetCellValue(Convert.ToDouble(value));
break;
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
cell.SetCellValue(Convert.ToInt64(value));
break;
default:
cell.SetCellValue(value.ToString());
break;
}
}
}
3. Web API Controller 示例
csharp
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
[ApiController]
[Route("api/[controller]")]
public class ExportController : ControllerBase
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthday { get; set; }
public bool IsActive { get; set; }
}
[HttpGet("export-users")]
public IActionResult ExportUsers()
{
// 模拟数据
var users = new List<User>
{
new User { Id = 1, Name = "张三", Birthday = new DateTime(1990, 1, 1), IsActive = true },
new User { Id = 2, Name = "李四", Birthday = new DateTime(1985, 5, 23), IsActive = false }
};
// 调用导出工具,生成Excel流
var stream = ExcelExportHelper.ExportToExcelStream(users, "用户列表");
// 返回文件流,设置Content-Type和文件名
string fileName = $"用户列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}
}