使用响应流来输出文件(适合导出文件使用,本文主要测试的是导出excel)

来源:互联网 发布:iptv与网络电视的区别 编辑:程序博客网 时间:2024/06/05 19:01
/////////这是个响应请求的方法@RequestMapping(method = RequestMethod.GET, value = "testResponseExportXLS")public void testResponseExportXLS(HttpServletRequest request,HttpServletResponse response) {try {exportXLSfromMaps("exportTest",response);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}

/////具体实现方法如下:

public void exportXLSfromMaps(String fileName, HttpServletResponse response)throws Exception {downloadFile(fileName + ".xls",response);java.io.OutputStream out = response.getOutputStream();WritableWorkbook workbook = null;WritableSheet sheet=null;workbook = Workbook.createWorkbook(out);sheet = workbook.createSheet("test Sheet", 0);// 添加label对象Label labelC = new Label(0, 0, "aaa");sheet.addCell(labelC);// 添加带有字型Formatting的对象WritableFont wf = new WritableFont(WritableFont.TIMES, 11, WritableFont.BOLD, true);WritableCellFormat wcfF = new WritableCellFormat(wf);jxl.write.Label labelCF = new jxl.write.Label(1, 0,"bbb", wcfF);sheet.addCell(labelCF);// 添加带有字体颜色Formatting的对象WritableFont wfc = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false,UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.RED);WritableCellFormat wcfFC = new WritableCellFormat(wfc);wcfFC.setAlignment(jxl.format.Alignment.CENTRE); Label labelCFC = new Label(2, 0,"ccc", wcfFC);sheet.addCell(labelCFC);sheet.mergeCells(0,0,0,1);sheet.mergeCells(2,0,3,0);// 添加带有字体颜色Formatting的对象WritableFont wf1 = new WritableFont(WritableFont.TIMES, 11, WritableFont.BOLD, true);WritableCellFormat wcfFC1 = new WritableCellFormat(wf1);Label labelCFC1 = new Label(3, 0,"ddd", wcfFC1);sheet.addCell(labelCFC1);// 2.添加Number对象jxl.write.Number labelN = new jxl.write.Number(0, 1, 12345);sheet.addCell(labelN);Label labelCFC2 = new Label(1, 1,"eee");sheet.addCell(labelCFC2);Label labelCFC3 = new Label(2, 1,"fff");sheet.addCell(labelCFC3);Label labelCFC4 = new Label(3, 1,"ggg");sheet.addCell(labelCFC4);workbook.write();   workbook.close();out.flush();out.close();}


 public void initAttachmentHeader(HttpServletResponse response){response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");response.setHeader("Content-Type", "application/force-download");response.setHeader("Content-Type", "application/octet-stream");response.setHeader("Content-Type", "application/download");response.setHeader("Cache-Control", "private, max-age=0, must-revalidate");response.setHeader("Pragma", "public");}public void downloadFile(String fileName,HttpServletResponse response){downloadFile(fileName, Const.nullInt,response);}public void downloadFile(String fileName, long length,HttpServletResponse response){initAttachmentHeader(response);response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");if(length != (long)Const.nullInt)    response.setHeader("Content-Length", String.valueOf(length));}