日期:2014-05-20 浏览次数:20763 次
public boolean exportExcel(ExportCustomerDto expDto) throws Exception { boolean isSuccess = false; //开始构造导出Excel文件名称 StringBuffer fileNameBuffer = new StringBuffer(); fileNameBuffer.append(CustomerConstants.EXPORT_CUS_FILENAME); SimpleDateFormat fmtDate = new SimpleDateFormat("yyyyMMddHHmmss"); fileNameBuffer.append(fmtDate.format(new Date())); fileNameBuffer.append((int) (10F * (new Random()).nextFloat())); fileNameBuffer.append(".xls"); //构造导出Excel文件名称完成 HSSFWorkbook workbook = new HSSFWorkbook(); // 产生工作簿对象 HSSFSheet sheet = workbook.createSheet(); // 产生工作表对象 // 设置第一个工作表的名称为firstSheet // 为了工作表能支持中文,设置字符编码为UTF_16 workbook.setSheetName(0, "客户批量导出", HSSFWorkbook.ENCODING_UTF_16); // 产生一行 HSSFRow row = sheet.createRow((short) 0); // 产生第一个单元格 String[] tableHead = {"姓名","电话","性别"................}; for (int i = 0; i < tableHead.length; i++) { HSSFCell cell = row.createCell((short) i); // 设置单元格内容为字符串型 cell.setCellType(HSSFCell.CELL_TYPE_STRING); // 为了能在单元格中写入中文,设置字符编码为UTF_16。 cell.setEncoding(HSSFCell.ENCODING_UTF_16); // 往第一个单元格中写入信息 cell.setCellValue(tableHead[i]); } List list = cusExportDao.cusExportList(expDto);//从数据库查的所有客户List int rowcount = 0; for (int j = 0; j < list.size(); j++) { ExportCustomerDto dto = (ExportCustomerDto) list.get(j); rowcount = j + 1; // 产生一行 HSSFRow row2 = sheet.createRow((short) rowcount); for (int k = 0; k < tableHead.length; k++) { HSSFCell cell2 = row2.createCell((short) k); // 设置单元格内容为字符串型 cell2.setCellType(HSSFCell.CELL_TYPE_STRING); // 为了能在单元格中写入中文,设置字符编码为UTF_16。 cell2.setEncoding(HSSFCell.ENCODING_UTF_16); // 往第一个单元格中写入信息 if (k == 0) { cell2.setCellValue(dto.getCustomerName()); } if (k == 1) { cell2.setCellValue(dto.getStrCustomerType()); } if (k == 2) { cell2.setCellValue(dto.getStrSex()); } if (k == 3) { cell2.setCellValue(dto.getPersonCardId()); } if (k == 4) { cell2.setCellValue(dto.getTelPhone()); } if (k == 5) { cell2.setCellValue(dto.getCellPhone()); } if (k == 6) { cell2.setCellValue(dto.getAddress()); } if (k == 7) { cell2.setCellValue(dto.getMailCode()); } if (k == 8) { cell2.setCellValue(dto.getEmail()); } if (k == 9) { cell2.setCellValue(dto.getViteDate()); } if (k == 10) { cell2.setCellValue(dto.getSaleGuid()); } // ////这里要加入要写到EXCEL表格中去的值 } } String fullFileName = System.getProperty("java.io.tmpdir") + "\\" + fileNameBuffer.toString(); expDto.setFilepath(fullFileName); System.out.println(expDto.getFilepath()); FileOutputStream fOut = new FileOutputStream(fullFileName); workbook.write(fOut); fOut.flush(); fOut.close(); isSuccess = true; return isSuccess; }