freemarker根据模板导出word_doc

使用方法:
1 制作word模板(可以包含图片)
2 将word保存为2003 xml文件
3 对key使用${}包起来
4 xml后缀改为ftl
5 在java类中填充数据(包含图片数据)

1、引用依赖

 <!--不同版本的依赖因springboot版本问题会在启动报错,调整freemarker版本即可-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>

2、工具类

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @Author 会飞的鱼
 * @Description 使用freemark生成word
 * @Date 2022/3/31 9:11
 * @Param 
 * @return 
 **/
public class FreemarkUtil {

//    public static void main(String[] args) {
//        FreemarkUtil.downLoadWordByTemplate(templateName,outFileName,dataMap,response);
//    }
    /**
     * @Author 会飞的鱼
     * @Description freemark初始化
     * @Date 2022/3/31 9:34
     * @Param [templateName]
     * @return
     **/
    public FreemarkUtil() {
        /*初始化freemarker模板*/
        configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding(Charset.forName("UTF-8").name());
        //必须加此参数,否则任意key的值为空freemark都会报错
        configuration.setClassicCompatible(true);
        configuration.setTemplateLoader(new ClassTemplateLoader(FreemarkUtil.class,"/template/"));
    }
    /**
     * @Author 会飞的鱼
     * @Description 根据模板下载文件
     * @Date 2022/3/31 10:00
     * @Param [templateName, wordName, dataMap]
     * @return void
     **/
    public static void downLoadWordByTemplate(String templateName,String wordName,Map<String,Object> dataMap,HttpServletResponse response){
        FreemarkUtil freemark = new FreemarkUtil();
        freemark.setTemplateName(templateName);
        freemark.setFileName(wordName+".doc");
        freemark.setFilePath("/temp");
        freemark.createWord(dataMap,response);
    }
    /**
     * @Author 会飞的鱼
     * @Description
     * @Date 2022/3/31 9:29
     * @Param [map:填充值]
     * @return void
     **/
    private void createWord(Map<String, Object> dataMap, HttpServletResponse response) {
        Template t = null;
        Writer out = null;
        FileOutputStream fos = null;
        try{
            t = configuration.getTemplate(templateName);
            File dir = new File(filePath);
            if (!dir.exists()&&!dir.isDirectory()) {
                dir .mkdir();
            }
            File outFile = new File(filePath + File.separator + fileName);
            if (!dir.exists()) {
                outFile.createNewFile();
            }
            fos = new FileOutputStream(outFile);
            OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");
            out = new BufferedWriter(oWriter);
            t.process(dataMap, out);
            out.close();
            fos.close();
            download(outFile, response);
        }catch(Exception e){
            e.printStackTrace();
        }

    }
    /**
     * @Author 会飞的鱼
     * @Description 下载并删除临时文件
     * @Date 2022/3/31 10:27
     * @Param [file, response]
     * @return void
     **/
    private void download(File file, HttpServletResponse response) {
        ServletOutputStream out = null;
        FileInputStream inputStream = null;
        try {
            String filename = file.getName();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition", "attachment; filename=" +
                    String.valueOf(URLEncoder.encode(filename, "UTF-8")));
            out = response.getOutputStream();
            inputStream = new FileInputStream(file);
            byte[] buffer = new byte[512];
            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();
            }
        }
    }

    /**
     * @Author 会飞的鱼
     * @Description 加载本地图片转成base64
     * @Date 2022/3/31 9:31
     * @Param imgUrl = "G:1.png"
     * @return java.lang.String
     **/
    public static String getImageStr(String imgUrl) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(imgUrl);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    /**
     * @Author 会飞的鱼
     * @Description 加载网络图片转成base64
     * @Date 2022/3/31 9:31
     * @Param [imgUrl]
     * @return java.lang.String
     **/
    public static String getImageStrByUrl(String url) {
        URL uri = null;
        HttpURLConnection httpUrl= null;
        InputStream in = null;
        byte[] data = null;
        try {
            uri = new URL(url);
            httpUrl = (HttpURLConnection) uri.openConnection();
            httpUrl.connect();
            in = httpUrl.getInputStream();
            data = new byte[in.available()];
            in.read(data);
            in.close();
            httpUrl.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }
    /**
     * freemark模板配置
     */
    private Configuration configuration;
    /**
     * freemark模板的名字
     */
    private String templateName;
    /**
     * 生成文件名
     */
    private String fileName;
    /**
     * 生成文件路径
     */
    private String filePath;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public String getTemplateName() {
        return templateName;
    }

    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }

}


3、模板放置位置

/resource/template/*

4、常用的几种填充类型

1)、单元格内容填充
${}占位

 <w:r wsp:rsidRPr="00F748BC">
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋"/>
                                        <wx:font wx:val="仿宋"/>
                                    </w:rPr>
                                    <w:t>${feature}</w:t>
                                </w:r>

2)、网络图片嵌入单元格
${pic.imgStr} 图片的base64转码字符串 ${pic_index}是因为我这里有多张图片循环展示取得不同的索引,单张图片可以不修改

<w:r wsp:rsidRPr="00F748BC">
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋"/>
                                        <wx:font wx:val="仿宋"/>
                                        <w:noProof/>
                                    </w:rPr>
                                    <w:pict>
                                        <v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f">
                                            <v:stroke joinstyle="miter"/>
                                            <v:formulas>
                                                <v:f eqn="if lineDrawn pixelLineWidth 0"/>
                                                <v:f eqn="sum @0 1 0"/>
                                                <v:f eqn="sum 0 0 @1"/>
                                                <v:f eqn="prod @2 1 2"/>
                                                <v:f eqn="prod @3 21600 pixelWidth"/>
                                                <v:f eqn="prod @3 21600 pixelHeight"/>
                                                <v:f eqn="sum @0 0 1"/>
                                                <v:f eqn="prod @6 1 2"/>
                                                <v:f eqn="prod @7 21600 pixelWidth"/>
                                                <v:f eqn="sum @8 21600 0"/>
                                                <v:f eqn="prod @7 21600 pixelHeight"/>
                                                <v:f eqn="sum @10 21600 0"/>
                                            </v:formulas>
                                            <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/>
                                            <o:lock v:ext="edit" aspectratio="t"/>
                                        </v:shapetype>
                                        <w:binData w:name="wordml://0_${pic_index}.png" xml:space="preserve">${pic.imgStr}</w:binData>
                                        <v:shape id="0_${pic_index}" o:spid="_x0000_i1025" type="#_x0000_t75" style="width:113.5pt;height:85pt;visibility:visible">
                                            <v:imagedata src="wordml://0_${pic_index}.png" o:title=""/>
                                        </v:shape>
                                    </w:pict>
                                </w:r>

3)、表格行循环
对w:tr进行循环 格式如下
<#list partOneList as one> </#list>

<#list partOneList as one>
<w:tr wsp:rsidR="000F0014" wsp:rsidRPr="00F748BC" wsp:rsidTr="00F748BC">
                        <w:trPr>
                            <w:trHeight w:val="1361"/>
                        </w:trPr>
                        <w:tc>
                            <w:tcPr>
                                <w:tcW w:w="1526" w:type="dxa"/>
                                <w:shd w:val="clear" w:color="auto" w:fill="auto"/>
                                <w:vAlign w:val="center"/>
                            </w:tcPr>
                            <w:p wsp:rsidR="000F0014" wsp:rsidRPr="00F748BC" wsp:rsidRDefault="00811D2B" wsp:rsidP="00F748BC">
                                <w:pPr>
                                    <w:pStyle w:val="af0"/>
                                    <w:jc w:val="center"/>
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋"/>
                                        <wx:font wx:val="仿宋"/>
                                    </w:rPr>
                                </w:pPr>
                                <w:r wsp:rsidRPr="00F748BC">
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋" w:hint="fareast"/>
                                        <wx:font wx:val="仿宋"/>
                                        <w:sz w:val="28"/>
                                        <w:sz-cs w:val="28"/>
                                    </w:rPr>
                                    <w:t>${one.post}</w:t>
                                </w:r>
                                <w:r wsp:rsidRPr="00F748BC">
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋"/>
                                        <wx:font wx:val="仿宋"/>
                                        <w:sz w:val="28"/>
                                        <w:sz-cs w:val="28"/>
                                    </w:rPr>
                                    <w:t></w:t>
                                </w:r>
                            </w:p>
                        </w:tc>
                        <w:tc>
                            <w:tcPr>
                                <w:tcW w:w="2125" w:type="dxa"/>
                                <w:shd w:val="clear" w:color="auto" w:fill="auto"/>
                                <w:vAlign w:val="center"/>
                            </w:tcPr>
                            <w:p wsp:rsidR="000F0014" wsp:rsidRPr="00F748BC" wsp:rsidRDefault="00811D2B">
                                <w:pPr>
                                    <w:pStyle w:val="af0"/>
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋"/>
                                        <wx:font wx:val="仿宋"/>
                                    </w:rPr>
                                </w:pPr>
                                <w:r wsp:rsidRPr="00F748BC">
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋" w:hint="fareast"/>
                                        <wx:font wx:val="仿宋"/>
                                        <w:sz w:val="28"/>
                                        <w:sz-cs w:val="28"/>
                                    </w:rPr>
                                    <w:t>${one.postProcess}</w:t>
                                </w:r>
                                <w:r wsp:rsidRPr="00F748BC">
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋"/>
                                        <wx:font wx:val="仿宋"/>
                                        <w:sz w:val="28"/>
                                        <w:sz-cs w:val="28"/>
                                    </w:rPr>
                                    <w:t></w:t>
                                </w:r>
                                <w:r wsp:rsidRPr="00F748BC">
                                    <w:t></w:t>
                                </w:r>
                                <w:r wsp:rsidRPr="00F748BC">
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋"/>
                                        <wx:font wx:val="仿宋"/>
                                        <w:sz w:val="28"/>
                                        <w:sz-cs w:val="28"/>
                                    </w:rPr>
                                    <w:t></w:t>
                                </w:r>
                            </w:p>
                        </w:tc>
                        <w:tc>
                            <w:tcPr>
                                <w:tcW w:w="2412" w:type="dxa"/>
                                <w:shd w:val="clear" w:color="auto" w:fill="auto"/>
                                <w:vAlign w:val="center"/>
                            </w:tcPr>
                            <w:p wsp:rsidR="000F0014" wsp:rsidRPr="00F748BC" wsp:rsidRDefault="00811D2B" wsp:rsidP="00F748BC">
                                <w:pPr>
                                    <w:widowControl/>
                                    <w:jc w:val="left"/>
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋"/>
                                        <wx:font wx:val="仿宋"/>
                                        <w:sz w:val="24"/>
                                    </w:rPr>
                                </w:pPr>
                                <w:r wsp:rsidRPr="00F748BC">
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋"/>
                                        <wx:font wx:val="仿宋"/>
                                        <w:sz w:val="28"/>
                                        <w:sz-cs w:val="28"/>
                                    </w:rPr>
                                    <w:t>${controlPoint}</w:t>
                                </w:r>
                                <w:r wsp:rsidR="00497902" wsp:rsidRPr="00F748BC">
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋" w:hint="fareast"/>
                                        <wx:font wx:val="仿宋"/>
                                        <w:sz w:val="24"/>
                                    </w:rPr>
                                    <w:t></w:t>
                                </w:r>
                            </w:p>
                        </w:tc>
                        <w:tc>
                            <w:tcPr>
                                <w:tcW w:w="2459" w:type="dxa"/>
                                <w:shd w:val="clear" w:color="auto" w:fill="auto"/>
                                <w:vAlign w:val="center"/>
                            </w:tcPr>
                            <w:p wsp:rsidR="000F0014" wsp:rsidRPr="00F748BC" wsp:rsidRDefault="007164DE" wsp:rsidP="00F748BC">
                                <w:pPr>
                                    <w:pStyle w:val="af0"/>
                                    <w:jc w:val="center"/>
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋"/>
                                        <wx:font wx:val="仿宋"/>
                                        <w:b/>
                                        <w:b-cs/>
                                        <w:sz w:val="28"/>
                                        <w:sz-cs w:val="28"/>
                                    </w:rPr>
                                </w:pPr>
                                <w:r wsp:rsidRPr="00F748BC">
                                    <w:rPr>
                                        <w:noProof/>
                                        <w:sz w:val="28"/>
                                        <w:sz-cs w:val="28"/>
                                    </w:rPr>
                                    <w:pict>
                                        <w:binData w:name="wordml://1_${one_index}.png" xml:space="preserve">${one.postImgShow}</w:binData>
                                        <v:shape id="一 ${one_index}" o:spid="_x0000_i1027" type="#_x0000_t75" style="width:112pt;height:84.5pt;visibility:visible">
                                            <v:imagedata src="wordml://1_${one_index}.png" o:title=""/>
                                        </v:shape>
                                    </w:pict>
                                </w:r>
                            </w:p>
                        </w:tc>
                    </w:tr>
                    </#list>

4)、单元格内容循环

<w:tc>
                            <w:tcPr>
                                <w:tcW w:w="2538" w:type="dxa"/>
                                <w:shd w:val="clear" w:color="auto" w:fill="auto"/>
                                <w:vAlign w:val="center"/>
                            </w:tcPr>
                            <#list picList as pic>
                            <w:p wsp:rsidR="000F0014" wsp:rsidRDefault="00F748BC" wsp:rsidP="00F748BC">
                                <w:pPr>
                                    <w:pStyle w:val="af0"/>
                                    <w:jc w:val="center"/>
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋"/>
                                        <wx:font wx:val="仿宋"/>
                                        <w:noProof/>
                                    </w:rPr>
                                </w:pPr>
                                <w:r wsp:rsidRPr="00F748BC">
                                    <w:rPr>
                                        <w:rFonts w:ascii="仿宋" w:h-ansi="仿宋"/>
                                        <wx:font wx:val="仿宋"/>
                                        <w:noProof/>
                                    </w:rPr>
                                    <w:pict>
                                        <v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f">
                                            <v:stroke joinstyle="miter"/>
                                            <v:formulas>
                                                <v:f eqn="if lineDrawn pixelLineWidth 0"/>
                                                <v:f eqn="sum @0 1 0"/>
                                                <v:f eqn="sum 0 0 @1"/>
                                                <v:f eqn="prod @2 1 2"/>
                                                <v:f eqn="prod @3 21600 pixelWidth"/>
                                                <v:f eqn="prod @3 21600 pixelHeight"/>
                                                <v:f eqn="sum @0 0 1"/>
                                                <v:f eqn="prod @6 1 2"/>
                                                <v:f eqn="prod @7 21600 pixelWidth"/>
                                                <v:f eqn="sum @8 21600 0"/>
                                                <v:f eqn="prod @7 21600 pixelHeight"/>
                                                <v:f eqn="sum @10 21600 0"/>
                                            </v:formulas>
                                            <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/>
                                            <o:lock v:ext="edit" aspectratio="t"/>
                                        </v:shapetype>
                                        <w:binData w:name="wordml://0_${pic_index}.png" xml:space="preserve">${pic.imgStr}</w:binData>
                                        <v:shape id="0_${pic_index}" o:spid="_x0000_i1025" type="#_x0000_t75" style="width:113.5pt;height:85pt;visibility:visible">
                                            <v:imagedata src="wordml://0_${pic_index}.png" o:title=""/>
                                        </v:shape>
                                    </w:pict>
                                </w:r>
                            </w:p>
                            </#list>
                        </w:tc>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值