public String writeExcel(List<MedicalWhiteList> MedicalWhiteList) { if(MedicalWhiteList == null || MedicalWhiteList.size() <= 0){ log.info("****不存在失败记录***"); return ""; } //创建HSSFWorkbook对象 HSSFWorkbook wb = new HSSFWorkbook(); //创建HSSFSheet对象 HSSFSheet sheet = wb.createSheet("sheet0"); //创建HSSFRow对象 HSSFRow row = sheet.createRow(0); //创建HSSFCell对象 HSSFCell cell=row.createCell(0); //设置单元格的值 cell.setCellValue("投保人手机号"); //输出Excel文件 row.createCell(1).setCellValue("投保人姓名"); row.createCell(2).setCellValue("投保人证件类型"); row.createCell(3).setCellValue("投保人证件号");for(int i = 0;i < MedicalWhiteList.size(); i++){ HSSFRow rowf = sheet.createRow(i+1); MedicalWhiteList m = MedicalWhiteList.get(i); rowf.createCell(0).setCellValue(m.getHolderMobile()); rowf.createCell(1).setCellValue(m.getHolderRealName()); rowf.createCell(2).setCellValue(m.getHolderCertiType()); rowf.createCell(3).setCellValue(m.getHolderCertiCode()); } //路径 Date now =new Date();//获取时间 String filePath = DateUtils.dateToString(now, "yyyyMMdd")+"/"; String absPath = Env.getProperty("MEDICALDATE_FILE_PATH")+filePath;// 保存路径 String time = DateUtils.dateToString(now, "yyyyMMddHHmmss"); String suffix = ".xls"; String csvName = time+suffix;//文件名称 String csvPath = absPath+csvName;//文件名称 //路径 File f = new File(absPath); if (!f.exists()) { f.mkdirs(); } FileOutputStream output = null; try { //明天换路径 output = new FileOutputStream(csvPath); } catch (FileNotFoundException e) { e.printStackTrace(); } try { wb.write(output); output.flush(); } catch (IOException e) { e.printStackTrace(); } return csvPath; }
注意java通过poi编写excel文件,需要工程共引入的jar有:
dom4j-1.6.1.jar
poi-3.9.jar
poi-ooxml-3.9.jar
poi-ooxml-schemas-3.9.jar
xmlbeans-2.3.0.jar
xml-resolver-1.2.jar
xmlschema-core-2.0.2.jar
xstream-1.3.1.jar