用java导出word并下载文件

来源:互联网 发布:js 时间格式转换 编辑:程序博客网 时间:2024/05/16 14:54

public void download() {Configuration configuration = new Configuration();configuration.setDefaultEncoding("utf-8");                                       //注意这里要设置编码configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");Template t = null;try {t = configuration.getTemplate("template1.ftl","utf-8");                  // 文件名 还有这里要设置编码} catch (Exception e) {e.printStackTrace();}File outFile = null;Writer out = null;String filename = "";try {filename = exportMap.get("unitname") + ""+exportMap.get("month")+"月资源运营报告";outFile = File.createTempFile(filename, ".doc");out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));                 //还有这里要设置编码} catch (Exception e1) {e1.printStackTrace();}try {t.process(exportMap, out);} catch (Exception e) {e.printStackTrace();}try {out.flush();out.close();} catch (IOException e) {e.printStackTrace();}InputStream fis = null;OutputStream toClient = null;try {fis = new BufferedInputStream(new FileInputStream(outFile));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();// 清空responseresponse.reset();// 设置response的Headerfilename = URLEncoder.encode(filename, "utf-8");                                  //这里要用URLEncoder转下才能正确显示中文名称response.addHeader("Content-Disposition", "attachment;filename=" + filename+".doc");response.addHeader("Content-Length", "" + outFile.length());toClient = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream");toClient.write(buffer);toClient.flush();} catch (Exception e) {e.printStackTrace();} finally{try {if(fis!=null){fis.close();}} catch (IOException e) {e.printStackTrace();}try {if(toClient!=null){toClient.close();}} catch (Exception e) {e.printStackTrace();}}}

首先装word2003,然后把word另存为xml文件,改其中的动态显示的部分为el表达式形式,如${unitname},然后再把xml文件改名成ftl文件做成模版,使用freemaker这些都不用多说。看代码.





原创粉丝点击