将List集合的数据写到一个Excel文件并导出示例:
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
List<UserInfo> listUser = new List<UserInfo>()
{
new UserInfo { name="1", id="1", phone="1r" },
new UserInfo { name="2", id="2", phone="2r" },
new UserInfo { name="3", id="3", phone="3r" },
new UserInfo { name="4", id="4", phone="4r" },
new UserInfo { name="5", id="5", phone="5r" },
};
1、//创建工作簿对象
IWorkbook workbook = new HSSFWorkbook();
2、//创建工作表
ISheet sheet = workbook.CreateSheet("onesheet");
IRow row0 = sheet.CreateRow(0);
row0.CreateCell(0).SetCellValue("用户Id");
row0.CreateCell(1).SetCellValue("用户名称");
row0.CreateCell(2).SetCellValue("用户备注信息");
for (int r = 1; r < listUser.Count; r++)
{
3、//创建行row
IRow row = sheet.CreateRow(r);
row.CreateCell(0).SetCellValue(listUser[r].id);
row.CreateCell(1).SetCellValue(listUser[r].name);
row.CreateCell(2).SetCellValue(listUser[r].phone);
row.CreateCell(3).SetCellValue(listUser[r].pwd);
}
//创建流对象并设置存储Excel文件的路径
using (FileStream url = File.OpenWrite(@"C:\Users\Administrator\Desktop\写入excel.xls"))
{
//导出Excel文件
workbook.Write(url);
Response.Write("<script>alert('写入成功!')</script>");
};
——————————分享End——————————