詳細教程:springboot導出word之freemarker導出--------手動繪製模板方式導出(一)

1.安裝MAVEN依賴

<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>

2.繪製word模板

  • 打開word,按照需求繪製模板內容
  • 保存爲xml格式
  • 手動更改保存後的文件格式爲ftl
  • 放入idea目錄下,格式化xml標籤,去掉${}前後的空格

3.編寫測試代碼

    private Configuration configuration = null;    

    public ExportWordService() {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
    }

   public void createDoc() throws UnsupportedEncodingException {

        // 填充的數據
        Map<String,String> dataMap=new HashMap<>();
        dataMap.put("name", "張三");
        dataMap.put("age", "18");

        //這裏我們的模板是放在templates包下面
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");

        Template t=null;
        try {
            //test.ftl爲要裝載的模板
            t = configuration.getTemplate("test.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 導出的文件名
        File outFile = new File("D:/outFilessa"+Math.random()*10000+".doc");
        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

        try {
            // 執行生成word
            t.process(dataMap, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

4.測試結果

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章