1、项目添加引用NPOI包。
2、尝试写一行数据写到excel中并导出。
public static void ExcelTest() { //导出:将数据库中的数据,存储到一个excel中 //1、查询数据库数据 //2、 生成excel //2_1、生成workbook //2_2、生成sheet //2_3、遍历集合,生成行 //2_4、根据对象生成单元格 HSSFWorkbook workbook = new HSSFWorkbook(); //创建工作表 var sheet = workbook.CreateSheet("信息表"); //创建标题行(重点) var row = sheet.CreateRow(0); //创建单元格 var cellid = row.CreateCell(0); cellid.SetCellValue("编号"); var cellname = row.CreateCell(1); cellname.SetCellValue("用户名"); var cellpwd = row.CreateCell(2); cellpwd.SetCellValue("密码"); var celltype = row.CreateCell(3); celltype.SetCellValue("类型"); FileStream file = new FileStream(@"C:\Users\ibm\信息表.xls", FileMode.CreateNew, FileAccess.Write); workbook.Write(file); file.Dispose(); }
3、运行方法之后。相应代码内容对应excel表格相应的地方
4、现在来模拟把表数据遍历写入到excel表格中。
创建表实体
public class User { public int Id { get; set; } public string Name { get; set; } public string pwd { get; set; } public string type { get; set; } }
public static void ExcelTest() { //导出:将数据库中的数据,存储到一个excel中 //1、查询数据库数据 User user1 = new User() { Id = 1, Name = "小明", pwd = "123123", type = "学生" }; User user2 = new User() { Id = 2, Name = "小红", pwd = "123123", type = "学生" }; User user3 = new User() { Id = 3, Name = "小绿", pwd = "123123", type = "学生" }; User user4 = new User() { Id = 4, Name = "小白", pwd = "123123", type = "老师" }; User user5 = new User() { Id = 5, Name = "小黑", pwd = "123123", type = "老师" }; User user6 = new User() { Id = 6, Name = "小蓝", pwd = "123123", type = "老师" }; List<User> list = new List<User>(); list.Add(user1); list.Add(user2); list.Add(user3); list.Add(user4); list.Add(user5); list.Add(user6); //2、 生成excel //2_1、生成workbook //2_2、生成sheet //2_3、遍历集合,生成行 //2_4、根据对象生成单元格 HSSFWorkbook workbook = new HSSFWorkbook(); //创建工作表 var sheet = workbook.CreateSheet("信息表"); //创建标题行(重点) 从0行开始写入 var row = sheet.CreateRow(0); //创建单元格 var cellid = row.CreateCell(0); cellid.SetCellValue("编号"); var cellname = row.CreateCell(1); cellname.SetCellValue("用户名"); var cellpwd = row.CreateCell(2); cellpwd.SetCellValue("密码"); var celltype = row.CreateCell(3); celltype.SetCellValue("类型"); //遍历集合,生成行 int index = 1; //从1行开始写入 for (int i = 0; i < list.Count; i++) { int x = index + i; var rowi = sheet.CreateRow(x); var id = rowi.CreateCell(0); id.SetCellValue(list[i].Id); var name = rowi.CreateCell(1); name.SetCellValue(list[i].Name); var pwd = rowi.CreateCell(2); pwd.SetCellValue(list[i].pwd); var type = rowi.CreateCell(3); type.SetCellValue(list[i].type); } FileStream file = new FileStream(@"C:\Users\ibm\信息表.xls", FileMode.CreateNew, FileAccess.Write); workbook.Write(file); file.Dispose(); }
5、运行ExcelTest()方法之后效果。
6、源码地址: https://gitee.com/linlijie071297/daily_learning.git
原文地址:https://www.cnblogs.com/linlijie/p/11701233.html
时间: 2024-10-16 09:31:53