一般创建HSSFWorkbook的过程写在业务层,这里为了减少代码暂时放在controller
@Controller public class PoiController {
//返回一个ResponseEntity类型 @RequestMapping("poidownloadtest.html") public ResponseEntity<byte[]> poiDownloadTest() throws UnsupportedEncodingException{ //创建一个excel并写入测试内容 HSSFWorkbook workbook=new HSSFWorkbook(); HSSFSheet sheet=workbook.createSheet("downloadTestSheet"); HSSFRow row=sheet.createRow(0); HSSFCell cell=row.createCell(0); cell.setCellValue("downTest");
//创建结束
//创建一个字节数组输出流对象 ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); try {
//将excel写入输出流 workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); } HttpHeaders headers=new HttpHeaders(); String fileName=new String("downloadTest.xls".getBytes("UTF-8"),"iso-8859-1"); headers.setContentDispositionFormData("attachment", fileName); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); ResponseEntity<byte[]> returnFile=new ResponseEntity<byte[]> (outputStream.toByteArray(),headers,HttpStatus.CREATED); try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } return returnFile; } }