将数据库中的数据导出到Excel
2013-09-12 08:45
218 查看
private void button1_Click(object sender, EventArgs e) { string sql = "select * from Employee"; using(SqlDataReader reader = DBHelper.ExecuteDataReader (sql,CommandType.Text)) { if (reader.HasRows) { //如果有读到数据 则创建一个Excel工作薄Workbook IWorkbook wk = new HSSFWorkbook(); //创建一个工作表Sheet ISheet employeeSheet = wk.CreateSheet("EmployeeMsg"); int rowIndex = 0; //用来维护行的索引 while (reader.Read()) { #region 循环一次就从数据库中获取一行数据 int id = reader.GetInt32(0); string name = reader.IsDBNull(1) ? null : reader.GetString(1); string gender = reader.IsDBNull(2) ? null : reader.GetString(2); int? age = reader.IsDBNull(3) ? null : (int?)reader.GetInt32(3); decimal? salary = reader.IsDBNull(4) ? null : (decimal?)reader.GetDecimal(4); string tel = reader.IsDBNull(5) ? null : reader.GetString(5); #endregion // 每循环一次 为Sheet中添加一行 IRow row = employeeSheet.CreateRow(rowIndex); // 为行添加单元格 row.CreateCell(0).SetCellValue(id); row.CreateCell(1).SetCellValue(name); row.CreateCell(2).SetCellValue(gender); // 报错 row.CreateCell(3).SetCellValue(age); 得做空值处理 if (age == null) { row.CreateCell(3, CellType.BLANK); // 如果值为null 则创建一个空单元格 } else { row.CreateCell(3).SetCellValue((int)age); } // row.CreateCell(4).SetCellValue(salary); if (salary == null) { row.CreateCell(4, CellType.BLANK); } else { row.CreateCell(4, CellType.NUMERIC).SetCellValue((double)salary); } if (tel == null) { row.CreateCell(5, CellType.BLANK); } else { row.CreateCell(5).SetCellValue(tel); } rowIndex++; } // 创建文件流 想Excel中写入数据 using (FileStream fs = File.OpenWrite("employee.xls")) { wk.Write(fs); MessageBox.Show("写入成功"); } } else { MessageBox.Show("表中无数据"); } } }
相关文章推荐
- C#数据库数据导出Excel通用方法
- JavaWeb中将数据从数据库导出到Excel表的实例
- 将数据库的数据导出到Excel表中
- poi+jdbc实现从数据库中导出表的数据字典结构(单个sheet和多个sheet供你选择),并且生成excel文档,作者:vipyhd
- JSP从数据库导出数据到Excel下载的实现
- 将数据库里的数据导出到EXCEL中的方法
- 数据库表格数据导出到excel方法总结
- 导出从数据库中查询到的所有的数据到Excel中
- C#后台制作之数据库(二、如何清除显示以及将数据库数据导出到excel表格文件中)
- Excel表格数据导入导出数据库
- oracle 数据库中数据导出到excel
- 导出sql server 数据库为Excel的数据字典的小工具
- 从数据库导出数据到word、excel、.txt
- java实现数据库数据导出到Excel并下载查看
- .net从将数据库中的数据导出到Excel格式的xml
- PHPexcel数据库导出数据实例
- 利用SQL*Loader将 Excel 数据导出到 Oracle 数据库中
- 从数据库导出数据到word、excel、.txt
- 从数据库导出数据到word、excel、.txt
- Excel导入oracle数据,oracle数据库导出excel