首页 > 代码库 > springMVC导出excel并提供下载

springMVC导出excel并提供下载

一般创建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; } }

 

springMVC导出excel并提供下载