//导出
- 引入jar包(poi-3.10-FINAL.jar);
编写方法 .java
@RequestMapping(value=”/exportExcel.do”,method{RequestMethod.POST,RequestMethod.GET})
public void exportExcel() throws Exception{HttpServletRequest request=ServletActionContext.getRequest(); HttpServletResponse response=ServletActionContext.getResponse(); String cityId = request.getParameter("regionid"); String countryId = request.getParameter("countyid"); String cityNm = request.getParameter("cityNm"); String countyNm = request.getParameter("countyNm"); String table = request.getParameter("table"); String title = request.getParameter("title")+".xls"; response.reset();// 清空输出流 response.setHeader("Content-disposition", "attachment; filename="+ new String(title.getBytes("GBK"),"ISO8859-1")); // 设定输出文件头 response.setContentType("application/msexcel");// 定义输出类型 BufferedOutputStream bos=null; OutputStream out=null; List list = new ArrayList(); String sql=""; HSSFWorkbook workbook=null; sql="select t.city_name,t.county_name"+ " from sdtower_eval_prop_all t where 1=1 "; if(cityId != null && !cityId.equals("")) sql += " and city_id = '" + cityId + "' "; if(countryId != null && !countryId.equals("")) sql += " and county_id = '" + countryId + "' "; list = dataPersistDao.searchByConnection(sql); String[] zdmc ={"地市","区县","等等"}; workbook = this.getExc(table,zdmc,list); // 写入数据到Excel out=response.getOutputStream(); bos=new BufferedOutputStream(out); workbook.write(bos); bos.flush(); out.close();
}
调用方法
public HSSFWorkbook getExc(String table,String[] zdmc,List list){HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("sheet1"); HSSFRow row = sheet.createRow(0);//创建第一行 HSSFCell cell = row.createCell(0);//第一列 for(int i=0;i<zdmc.length;i++){ cell = row.createCell(i); //创建第一列 cell.setCellValue(new HSSFRichTextString(zdmc[i])); } if(list!=null&&list.size()>0){ for (int i = 0; i < list.size(); i++) { Object[] obj= (Object[]) list.get(i); row=sheet.createRow(i+1);//创建第i+1行 for(int j=0;j<obj.length;j++){ cell=row.createCell(j);//创建第一列 if(obj[j]!=null){ cell.setCellValue(obj[j].toString()); }else{ cell.setCellValue(""); } } } } return workbook;
}