当前位置: 代码迷 >> J2EE >> excel解决办法
  详细解决方案

excel解决办法

热度:9920   发布时间:2013-02-25 21:40:47.0
excel
public void downloadExcel(List<RepairCatalogSearchResultsVO> rowDataList, String fileName) throws CROSException{
ServletOutputStream servletOutputStream = null;
FileOutputStream output = null;
FileInputStream input = null;
File exportFile = null;

try {
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet sheet = workBook.createSheet("results");
sheet.setDefaultColumnWidth((short)20);
HSSFFont font1 = workBook.createFont();
font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

/*HSSFCellStyle titleBold = workBook.createCellStyle();
titleBold.setAlignment(HSSFCellStyle.ALIGN_CENTER);
titleBold.setWrapText(true);
titleBold.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
titleBold.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
HSSFFont font = workBook.createFont();
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
titleBold.setFont(font);*/


HSSFRow row = sheet.createRow((short) 0);
row.createCell((short)0).setCellValue("ATA");
//row.getCell((short)0).setCellStyle(titleBold);

row.createCell((short)1).setCellValue("componentDesc");
//row.getCell((short)1).setCellStyle(titleBold);


Iterator<RepairCatalogSearchResultsVO> ite = rowDataList.iterator();
int index = 1;
while (ite.hasNext()) {
RepairCatalogSearchResultsVO vo = ite.next();
row = sheet.createRow(index);
row.createCell((short)0);
row.getCell((short)0).setCellValue(vo.getAtaNum());

row.createCell((short)1);
row.getCell((short)1).setCellValue(vo.getComponentDesc());

index++;
}

String filePath = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRealPath("/")
+ "WEB-INF\\" + System.currentTimeMillis() + "_" + fileName;
output = new FileOutputStream(filePath);
workBook.write(output);
output.flush();
output.close();

//下面写不写
exportFile = new File(filePath);
HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
servletOutputStream = httpServletResponse.getOutputStream();
httpServletResponse.setHeader("Content-disposition",
"attachment; filename=" + fileName);
httpServletResponse.setContentLength((int) exportFile.length());
httpServletResponse.setContentType("application/x-download");
httpServletResponse.setContentType("application/vnd.ms-excel");
byte[] buffer = new byte[1024];
int flag = 0;
input = new FileInputStream(exportFile);
while ((flag = input.read(buffer)) > 0) {
servletOutputStream.write(buffer, 0, flag);
}
servletOutputStream.flush();
} catch (FileNotFoundException notFoundException) {
} catch (IOException ioException) {
} catch (Exception exception) {
} finally {
try {
if (output != null) {
output.close();
}

if (input != null) {
input.close();
}

if (servletOutputStream != null) {
  相关解决方案