NPOI下载地址:http://npoi.codeplex.com/
导出Excel文件源码:
public static void RenderToExcel<T>(List<T> datas)
{
MemoryStream ms = new MemoryStream();
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("导出数据");
IRow headerRow = sheet.CreateRow(0);
int rowIndex = 1, piIndex = 0;
Type type = typeof(T);
PropertyInfo[] pis = type.GetProperties();
int pisLen = pis.Length - 2;//减2是多了2个外键引用
PropertyInfo pi = null;
string displayName = string.Empty;
while (piIndex < pisLen)
{
pi = pis[piIndex];
displayName = ExcelService.GetDisplayName(type, pi.Name);
if (!displayName.Equals(string.Empty))
{//如果该属性指定了DisplayName,则输出
try
{
headerRow.CreateCell(piIndex).SetCellValue(displayName);
}
catch (Exception)
{
headerRow.CreateCell(piIndex).SetCellValue("");
}
}
piIndex++;
}
foreach (T data in datas)
{
piIndex = 0;
IRow dataRow = sheet.CreateRow(rowIndex);
while (piIndex < pisLen)
{
pi = pis[piIndex];
try
{
dataRow.CreateCell(piIndex).SetCellValue(pi.GetValue(data, null).ToString());
}
catch (Exception)
{
dataRow.CreateCell(piIndex).SetCellValue("");
}
piIndex++;
}
rowIndex++;
}
workbook.Write(ms);
FileStream dumpFile = new FileStream(@"C:\\1.xls", FileMode.Create, FileAccess.ReadWrite);
ms.WriteTo(dumpFile);
ms.Flush();
ms.Position = 0;
dumpFile.Close();
}
注:
1、引用压缩包中的NPOI.dll文件到对应项目中。
2、在文件夹中创建一个空excel文件,该文件需要添加对应.net用户的权限,也可直接添加Everyone的读写权限。