2013-03-05 13:00 java 后台 Excel 文件生成后转化为字节流

java excel 使用 poi组件, HSSFWorkbook workBook = new HSSFWorkbook();

对于workBook生成字节流,很容易发现有个workBook .getBytes(),但是,是不可用的,下载以后打不开,

如果下载,正确的写法为

workBook.write(response.getOutputStream());

如果转化为字节流:

ByteArrayOutputStream os = new ByteArrayOutputStream();

try {

workBook.write(os);

ByteArray bytes = os.toByteArray();

String fileName = "xxx.xls";

runData.getResponse().reset();

runData.getResponse().setContentType("application/msexcel;charset=utf-8");

runData.getResponse().setHeader("Content-disposition", "attachment;filename= "+ fileName);

 

runData.getResponse().getOutputStream().write(bytes.getRawBytes());

runData.getResponse().getOutputStream().flush();

runData.getResponse().getOutputStream().close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

 

dwr的写法

:ByteArrayOutputStream os = new ByteArrayOutputStream();
  try
  {
   hssfWorkbook.write(os);
   return new FileTransfer(new String("XXXX.xls".getBytes(),"iso8859-1"),  "application/ms-excel", os.toByteArray());
  }
  catch (IOException e)
  {
   e.printStackTrace();
  }

你可能感兴趣的:(Excel)