java 根据模板,导出word并提供下载
java+springmvc實現(xiàn)根據(jù)freemarker模板導出word模板。模板使用的后綴可以是:.xml,也可以是.ftl。
步驟1,引入freemarker的jar包。
步驟2,制作模板文件。(紅框中的內(nèi)容是為了替換使用)
另存為xml格式,
找到xml文件,右鍵用editplus打開,找到紅框的標記1,標記2進行修改。
如果是表格的話,表頭的第一行需要保留。
表格的主體部分需要保留一個,
這里eList是從后臺賦值的一個集合,${e_index+1}是根據(jù)<#list eList as e>這個別名+_index得到,用法基本與el表達式用法相同。
這樣一個模板就完成了,將模板復制進項目中即可,后綴是什么不重要,重要的是我們用freemarker解析。
步驟4,java后臺代碼。
@RequestMapping("/test/toWord") public ModelAndView toWord(HttpServletRequest request, HttpServletResponse response) throws IOException{File file = createDoc();response.setContentType("text/html;charset=utf-8");request.setCharacterEncoding("UTF-8");java.io.BufferedInputStream bis = null;java.io.BufferedOutputStream bos = null;try {long fileLength = file.length();response.setContentType("application/msword");response.setHeader("Content-disposition", "attachment; filename="+ URLEncoder.encode("測試的,統(tǒng)計-導出時間"+DateTimeUtils.getDateTime("yyyyMMddHHmmss")+".doc", "utf-8"));response.setHeader("Content-Length", String.valueOf(fileLength));bis = new BufferedInputStream(new FileInputStream(file));bos = new BufferedOutputStream(response.getOutputStream());byte[] buff = new byte[2048];int bytesRead;while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {bos.write(buff, 0, bytesRead);}} catch (Exception e) {e.printStackTrace();} finally {if (bis != null)bis.close();if (bos != null)bos.close();}return null; }private File createDoc(){// 創(chuàng)建數(shù)據(jù)Map<String,Object> dataMap = new HashMap<String, Object>();dataMap.put("cwlx", "測試的");List<?> eList = new ArrayList<?>();// 這里是獲取list列表的方法dataMap.put("czsj",DateTimeUtils.getDateTime("yyyyMMddHHmmss"));// 這里是獲取當前時間的一種方式,可以根據(jù)自己程序自行修改dataMap.put("eList", eList);// 獲取模板Configuration configuration = new Configuration();configuration.setDefaultEncoding("utf-8");configuration.setClassForTemplateLoading(this.getClass(), "/tpl");Template t = null;String name = "temp"+(int)(Math.random()*1000)+".doc";File file = new File(name);try {t = configuration.getTemplate("model.xml");t.setEncoding("UTF-8");Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name),"UTF-8"));t.process(dataMap, out);out.close();} catch (IOException e) {e.printStackTrace();} catch (TemplateException e) {e.printStackTrace();}return file; }在前臺頁面是需要做的就是發(fā)送一個鏈接就可以了。
特別注意,
經(jīng)常忽視的問題,編碼的問題,這里需要統(tǒng)一編碼。
如果出現(xiàn)了word文件不能打開的情況,建議看一下后臺文件是否報錯。如果后臺沒有報錯的話,建議用editplus打開word的文檔,查看文檔中是否有亂碼的情況。
筆者第一次使用的時候,經(jīng)常出現(xiàn)word文件不能打開的問題,于是我在editplus中打開,發(fā)現(xiàn)部分漢字是亂碼的,加了上圖紅框中的默認編碼的設(shè)置之后就可以了。
轉(zhuǎn)自:java 根據(jù)模板,導出word并提供下載 - firework - 博客園 http://www.cnblogs.com/mini-firework/p/4934337.html
總結(jié)
以上是生活随笔為你收集整理的java 根据模板,导出word并提供下载的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ie工具internet选项安全自定义级
- 下一篇: 阿里云服务器配置参数详细说明文档