springboot使用freemaker導出word文檔


1、Controller

/**
     * 下載協議到word模板
     */
    @GetMapping("/downloadtest")
    public void downloadtest(Test test, HttpServletRequest request, HttpServletResponse response) {
        //數據賦值
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("name", test.getName());

        String templateName = "model.ftl";
        String filePath = "E:\\modelfile";
        String fileName = "Test.doc";
        try {
            FreemarkerUtil.createWord(dataMap, templateName, filePath, fileName);//數據和模板合並生成word

            //下載文件
            // 本地資源路徑
            String localPath = filePath;
            // 數據庫資源地址
            String downloadPath = "E:/modelfile/Test.doc";
            // 下載名稱
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
            FileUtils.writeBytes(downloadPath, response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件下載失敗");
        }
    }

    //處理特殊字符 增加換行
    public String handleData(String data) {
        data = data.replaceAll("&", "&amp;")
                .replaceAll("<", "&lt;").replaceAll(">", "&gt;")
                .replaceAll("<LF>", "&lt;LF&gt;<w:p></w:p>");
        return data;
    }

  2、html

 <form  method="GET" action="/system/test/downloadtest">
                                <input  id="name" name="name"  th:value="${data.name}" type="hidden">

                                <input type="submit" value="協議下載" />
                            </form>

  3、創建Freemarker操作類

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

public class FreemarkerUtil {
    /**
     * 生成word文件
     * @param dataMap word中需要展示的動態數據,用map集合來保存
     * @param templateName word模板名稱,例如:model.ftl
     * @param filePath 文件生成的目標路徑,例如:E:\\freemarker
     * @param fileName 生成的文件名稱,例如:Test.doc
     */   public static void createWord(Map dataMap, String templateName, String filePath, String fileName) {
        try {
            //創建配置實例
            Configuration configuration = new Configuration();

            //設置編碼
            configuration.setDefaultEncoding("utf-8");

            //ftl模板文件
            configuration.setClassForTemplateLoading(FreemarkerUtil.class, "/");

            //獲取模板
            Template template = configuration.getTemplate(templateName);

            //輸出文件
            File outFile = new File(filePath + File.separator + fileName);

            //如果輸出目標文件夾不存在,則創建
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }

            //將模板和數據模型合並生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));


            //生成文件
            template.process(dataMap, out);

            //關閉流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  4、引入pom依賴

<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.22</version>
		</dependency>

  5、下載模板放入 resource下

    創建模板:先創建一個word文檔,使用notepad++轉換成.xml文件,再直接改后綴改成.ftl格式。


免責聲明!

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



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