从数据库中读取数据到Excel

//得到文本框的路径 string path = txtFilePath.Text; 读取数据库数据到文件中 //List list = classBLL.GetAllClass(0); 进行系列化与反系列化 //foreach (Model.Class item in list) //{ // using (FileStream fs = new FileStream(path, FileMode.Create)) // { // BinaryFormatter bf = new BinaryFormatter();//进行系列化 // bf.Serialize(fs, item); // } // //using() // using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) // { // BinaryFormatter bf = new BinaryFormatter();//进行系列化 // Model.Class c = bf.Deserialize(fs) as Model.Class; // } //} //msgDiv.MsgDivShow("反系列化成功", 2); //创建一个工作本 IWorkbook workbook = new HSSFWorkbook(); //创建一个工作表 ISheet sheet = workbook.CreateSheet("sheet"); //创建行 每一行就是一个班级对象 IRow rowTitle = sheet.CreateRow(0); //创建第一列 班级ID ICell cell = rowTitle.CreateCell(0, CellType.NUMERIC); cell.SetCellValue("班级ID"); //创建班级名称 cell = rowTitle.CreateCell(1, CellType.STRING); cell.SetCellValue("班级名称"); //创建总人数 cell = rowTitle.CreateCell(2, CellType.NUMERIC); cell.SetCellValue("班级人数"); //创建添加时间 cell = rowTitle.CreateCell(3, CellType.STRING); cell.SetCellValue("添加时间"); //创建表格标题 //得到datagradview中的数据 List list = dgvClasses.DataSource as List; if (list == null) { msgDiv.MsgDivShow("没有可导出的数据", 2); return; } //遍历集合得到对象 for (int i=1;i<list.Count;i++) { Model.Class model = list[i]; //创建行 每一行就是一个班级对象 IRow row = sheet.CreateRow(i); //创建第一列 班级ID ICell cellTitle = row.CreateCell(0,CellType.NUMERIC); cellTitle.SetCellValue(model.CID); //创建班级名称 cellTitle = row.CreateCell(1, CellType.STRING); cellTitle.SetCellValue(model.CName); //创建总人数 cellTitle = row.CreateCell(2, CellType.NUMERIC); cellTitle.SetCellValue(model.CCount); //创建添加时间 cellTitle = row.CreateCell(3, CellType.STRING); cellTitle.SetCellValue(model.CAddTime); } //写入硬盘中 using (FileStream fs = new FileStream(path, FileMode.Create)) { workbook.Write(fs); msgDiv.MsgDivShow("写入成功", 2); } }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值