Java使用模板導出word文檔


Java使用模板導出word文檔

  • 需要導入freemark的jar包
  1. 使用word模板,在需要填值的地方使用字符串代替,是因為word轉換為xml文件時查找不到要填入內容的位置。盡量不要在寫字符串的時候就加上${},xml文件會讓它和字符串分離。
    比如: 姓名| name
  2. 填充完之后,把word文件另存為xml文件,然后使用notepad 等編輯軟件打開,打開之后代碼很多,也很亂,根本看不懂,其實也不用看懂哈,搜索找到你要替換的位置的字符串,比如name,然后加上 ${} ,變成 ${name} 這樣,然后就可以保存了,之后把保存的文件名后綴替換為.ftl。模板就ok了。
  3. 有個注意事項,這里的值一定不可以為空,否則會報錯,freemark有判斷為空的語句,這里示例一個,根據個人需求,意思是判斷name是否為空,trim之后的lenth是否大於0:

    <#if name?default("")?trim?length gt 0>
    <w:t>${name}</w:t>
    </#if>

  4. 如果在本地的話可以直接下載下來,但是想要在通過前端下載的話那就需要先將文件下載到本地,當作臨時文件,然后在下載文件。接下來上代碼,示例:
public void downloadCharge(String  name, HttpServletRequest request, HttpServletResponse response) {
     
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try { //模板存放位置
            InputStream inputStream = this.getClass().getResourceAsStream("/template/report/XXX.ftl");
            Template t = new Template(null, new InputStreamReader(inputStream));
            String filePath = "tempFile/";
            //導出文件名
            String fileName = "XXX.doc";
	    //文件名和路徑不分開寫的話createNewFile()會報錯
            File outFile = new File(filePath + fileName);
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            if (!outFile.exists()) {
                outFile.createNewFile();
            }

            Writer out = null;
            FileOutputStream fos = null;
            fos = new FileOutputStream(outFile);
            OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");
            //這個地方對流的編碼不可或缺,使用main()單獨調用時,應該可以,但是如果是web請求導出時導出后word文檔就會打不開,並且包XML文件錯誤。主要是編碼格式不正確,無法解析。
            //out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
            out = new BufferedWriter(oWriter, 1024 * 10);
            t.process(map, out);
            out.close();
            fos.close();
	     //調用download方法下載臨時文件
            download(outFile, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

這里下載的文件名是亂碼,個人能力有限,找了很多方法沒有解決掉,如果你有好的解決方法可以告訴我,感謝

 /**
     * 下載生成的word文件並刪除臨時文件
     */
    private void download(File file, HttpServletRequest request, HttpServletResponse response) {

        ServletOutputStream out = null;
        FileInputStream inputStream = null;
        try {
            String filename = file.getName();
            String userAgent = request.getHeader("User-Agent");
            // 針對IE或者以IE為內核的瀏覽器:
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                filename = java.net.URLEncoder.encode(filename, "UTF-8");
            } else {
                // 非IE瀏覽器的處理:
                // filename = URLEncoder.encode(filename, "UTF-8");
                filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=\"%s\"", filename));
            response.setContentType("application/download");
            response.setCharacterEncoding("UTF-8");
            out = response.getOutputStream();
            inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024 * 10];
            int bytesToRead = -1;
            // 通過循環將讀入的Word文件的內容輸出到瀏覽器中
            while ((bytesToRead = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) out.close();
                if (null != inputStream) inputStream.close();
                file.delete();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

這樣,參照模板的文件就下載下來了
寫的有點亂,請擔待,上面制作模板部分百度一大堆,不理解的可以百度哈


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM