xiaobeth

poi导出excel

步骤一:从数据库获取要导出的数据

String sql = "select * from table";
 List<Record> l1 = Db.find(sql);
 
步骤二:将模板内容复制到新建excel文件
 String oldpath = PathKit.getWebRootPath() + "/template/模板.xls";
 String newpath = PathKit.getWebRootPath() + "/template/新数据.xls";
  copyFile(oldpath, newpath);
   File file = new File(newpath);
 
  try {
步骤三: 创建Excel的工作书册
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
    HSSFWorkbook wb = new HSSFWorkbook(fs); // 创建Excel的工作书册
 
步骤四:创建Excel的工作sheet,对应到一个excel文档的tab
  HSSFSheet sheet = wb.getSheetAt(0);   //创建sheet
 
步骤五:将数据导出到excel文件
     int i = 1;
     for (Record r : l1) {
      String plantcode = r.getStr("plantcode");  //依次取出数据库中每一条数据的需要列
      String unitcode = r.getStr("unitcode");
      HSSFRow row = sheet.createRow(i); // 依次创建Excel的sheet的行
      row.createCell(0);    //创建列
      row.createCell(1);
      row.createCell(2);
      row.getCell(0).setCellValue(i);    //给创新创建行的相应列赋值
      row.getCell(1).setCellValue(plantcode);
      row.getCell(2).setCellValue(unitcode );
      i++;
     }
    }
     } catch (Exception e) {
    e.printStackTrace();
    return e.getMessage();
   }
 
注:1.若模板的某些单元格中已经有数据,只需给部分单元格赋值,则直接获取行,再获取需要的单元格并赋值即可(既用数据库中的数据与模板的每一条数据进行匹配,匹配成功,则给成功的记录赋值)。
       2.若获取的单元格为空,则可在单元格中输入空格解决。
       3.单元格的字符串做相等比较时,要去除空格。

posted on 2016-01-14 10:12  xiaobeth  阅读(196)  评论(0)    收藏  举报