java 操作excel文件之系列二:《读取数据库的内容写入excel文件》

要写入的文件:test.xls(sheet名也叫:test)

    public void createExcelTest(){

//创建excel,设置sheet,表头, HSSFWorkbook workbook=new HSSFWorkbook(); HSSFSheet sheet=workbook.createSheet("test"); HSSFRow row=sheet.createRow(0); HSSFCell cell=row.createCell(0); cell.setCellValue("序号"); cell=row.createCell(1); cell.setCellValue("查询词"); cell=row.createCell(2); cell.setCellValue("cityid"); cell=row.createCell(3); cell.setCellValue("cityname"); cell=row.createCell(4); cell.setCellValue("showtype"); cell=row.createCell(5); cell.setCellValue("cateid");
//操作数据库,从数据库中取出数据 Calendar c = Calendar.getInstance(); Date date = new Date(); c.setTime(date); c.add(Calendar.DAY_OF_YEAR, -30); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); String time = simpleDateFormat.format(c.getTime()); System.out.println(time); String sql = String.format("select `keywords`,`cityid` from testTable where dt>%s limit 10000", time); logger.info("执行的sql:" + sql); List<List<Object>> results = HiveQuery.executeSql(sql);

//将数据库查询结果写入excel,创建行和单元格 for(int i=0;i<results.size();i++) { HSSFRow row1=sheet.createRow(i+1); row1.createCell(0).setCellValue(i); row1.createCell(1).setCellValue(results.get(i).get(0).toString()); row1.createCell(2).setCellValue(results.get(i).get(1).toString()); } try { FileOutputStream fos = new FileOutputStream("test.xls"); workbook.write(fos); fos.close(); }catch (IOException e){ e.printStackTrace(); } }

  

下面是创建好的excel文件的内容:

 

posted on 2017-07-18 15:35  朱古力88  阅读(784)  评论(0编辑  收藏  举报