POI生成Excel及下载

输出excle到指定目录

		HSSFWorkbook workbook = new HSSFWorkbook();HSSFSheet currSheet = workbook.createSheet("CommonQueryData");HSSFRow row=currSheet.createRow(1);HSSFCell cell= row.createCell(0);cell.setCellValue("1");FileOutputStream outputStream= new FileOutputStream("d://abc.xls");workbook.write(outputStream);outputStream.flush();outputStream.close();//把workbook的内容输出到指定文件

把数据写到excel文件输出到指定路径后可以用于测试,查看自己生成的workbook内容是否正确。

 window.open(url, 'download');  //导出

下载excel

public static void createExcelFileCommonQuery(List<Map<String, Object>> resultList, HttpServletResponse response, Map<String, String> columnsMap,Map<String, String> paramMap ) throws BusinessException{HSSFWorkbook workbook = createExcelCommonQuery(resultList,columnsMap);response.setCharacterEncoding("UTF-8");		response.setContentType("application/vnd.ms-excel");OutputStream os=null;String fileName=paramMap.get("fileName");response.setHeader("Content-disposition","attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));os = response.getOutputStream();workbook.write(os);os.flush();os.close();}	

poi生成excel,

/***** 通用查询导出* @param resultList*/
private static HSSFWorkbook createExcelCommonQuery(List<Map<String, Object>> excelList,Map<String,String> columnsMap){/**columnsMap:key valuename 姓名(表格第一行标题行)sex  男addr 住址**/HSSFWorkbook workbook = new HSSFWorkbook();CellStyle styleboder = workbook.createCellStyle();CellStyle titlestyle = workbook.createCellStyle();//设置边框styleboder.setBorderLeft(HSSFCellStyle.BORDER_THIN);styleboder.setBorderRight(HSSFCellStyle.BORDER_THIN);styleboder.setBorderTop(HSSFCellStyle.BORDER_THIN);styleboder.setBorderBottom(HSSFCellStyle.BORDER_THIN);			HSSFSheet currSheet = workbook.createSheet("CommonQueryData");//改变背景色titlestyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);titlestyle.setFillForegroundColor((short)43);titlestyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());titlestyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);titlestyle.setBorderRight(HSSFCellStyle.BORDER_THIN);titlestyle.setBorderTop(HSSFCellStyle.BORDER_THIN);titlestyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);//改变背景色for(int i=0; i<excelList.size()+1;i++){HSSFRow row = currSheet.createRow(i);Map<String, Object> item=new HashMap<String, Object>();if(i==0){item = excelList.get(i);}else{item = excelList.get(i-1);}int j=0;for(Iterator<String> iter = item.keySet().iterator();iter.hasNext();){					String key = iter.next();Object value = item.get(key);//判断columnsMap是否包含属性字段	boolean isExist = columnsMap.containsKey(key);if(isExist){HSSFCell cell = row.createCell(j++);if(i==0){/**标题**///写标题行cell.setCellValue(columnsMap.get(key));cell.setCellStyle(titlestyle);}else{//写内容行cell.setCellStyle(styleboder);cell.setCellValue(null == value ? "" : value.toString());}}}}return workbook;
}

参考:http://www.yiibai.com/apache_poi/apache_poi_cells.html

参考:http://www.cnblogs.com/jyh317/p/3817171.html