java springboot easy-poi 导出word文档(word做为模板 支持doc、docx)

前言:
本文章的方法支持docx文档作为模板,并且

支持doc文档作为模板!!!
支持doc文档作为模板!!!
支持doc文档作为模板!!!
重要的事情说三遍

word模板语法可以去百度一下
大概就是 {{map的key}} 这个格式
在util的方法中传入一个map或者hashmap 以键值对的方式插入数据
比如account:20,那么在下面account中的值便是20
java springboot easy-poi 导出word文档(word做为模板 支持doc、docx)_第1张图片

pom.xml


        <dependency>
            <groupId>org.freemarkergroupId>
            <artifactId>freemarkerartifactId>
            <version>2.3.23version>
        dependency>
        <dependency>
            <groupId>org.jeecggroupId>
            <artifactId>easypoi-baseartifactId>
            <version>2.3.1version>
        dependency>
        <dependency>
            <groupId>org.jeecggroupId>
            <artifactId>easypoi-webartifactId>
            <version>2.3.1version>
        dependency>
        <dependency>
            <groupId>org.jeecggroupId>
            <artifactId>easypoi-annotationartifactId>
            <version>2.3.1version>
        dependency>
        <dependency>
            <groupId>org.jfreegroupId>
            <artifactId>jfreechartartifactId>
            <version>1.0.19version>
        dependency>
        <dependency>
            <groupId>com.itextpdfgroupId>
            <artifactId>itext-asianartifactId>
            <version>5.2.0version>
        dependency>
        
        <dependency>
            <groupId>com.artofsolvinggroupId>
            <artifactId>jodconverterartifactId>
            <version>2.2.2version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poiartifactId>
            <version>3.17version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-scratchpadartifactId>
            <version>3.17version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-ooxmlartifactId>
            <version>3.17version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-ooxml-schemasartifactId>
            <version>3.17version>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
            <version>3.7version>
        dependency>

PathUtils.java

package com.protectzaizai.schoolcardoa.utils;

import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Author: 动感小⑦
 * @Date:2020/2/22 10:56
 */
public class PathUtils {
    //获取springboot项目的根目录
    public static String getRootPath() throws FileNotFoundException {
        //获取跟目录
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) path = new File("");
        System.out.println("rootPath:" + path.getAbsolutePath());
        return path.getAbsolutePath();
    }

    //获取springboot项目的static目录
    public static String getStaticPath() throws IOException {
        //获取static目录  注意部署的时候更改路径/
        String path = null;
        if (getSeparator().equals("/")) {                //linux系统
            path = getRootPath() + "/static";
        } else {
            path = getRootPath() + "\\static";
        }
        System.out.println("staticPath:" + path);
        return path;
    }

    //跨平台路径斜杠分隔符获取
    public static String getSeparator() {
        return File.separator;
    }

    // 获取文件后缀名
    public static String getSuffix(String path) {
        return path.substring(path.lastIndexOf(".") + 1);
    }
}

DocUtils.java

/**
     * 向word模板中插入数据,生成新word
     * 切记这里的path是模板路径,modelPath 是word模板的路径,outPutPath是输出路径
     * 请注意导入的model是doc导出的就是doc 如果设置成docx就会错误,docx导出的是docx
     *
     * @param map
     * @param modelPath
     * @throws Exception
     */
    public static void generateWord(HashMap map, String modelPath, String outPutPath) throws Exception {
        //因为空格无法输出,过滤一下空格 用-代替
        Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = iter.next();
            Object key = entry.getKey();
            Object val = entry.getValue();
            if (val.equals("") || val == null) {
                map.put((String) key, "-");         //空格无法输出
            }
        }

        //先创建文件
        File file = new File(outPutPath);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        try {
            //获取文件后缀
            String suffix = PathUtils.getSuffix(modelPath);
            if (suffix.equals("docx")) {
                XWPFDocument doc = WordExportUtil.exportWord07(modelPath, map);
                FileOutputStream fos = new FileOutputStream(file);
                doc.write(fos);
                fos.close();
            } else if (suffix.equals("doc")) {
                HWPFDocument docu = new HWPFDocument(new FileInputStream(modelPath));
                Range range = docu.getRange();
                getRunge(range, map);
                FileOutputStream stream = new FileOutputStream(file);
                docu.write(stream);
                stream.flush();
                stream.close();
            }
        } catch (Exception e) {
            System.out.println("文件后缀名有误!");
            e.printStackTrace();
        }
    }
	
	 public static void getRunge(Range range, Map<String, Object> map) {
        TableIterator tableIter = new TableIterator(range);
        Table table;
        TableRow row;
        TableCell cell;
        while (tableIter.hasNext()) {
            table = tableIter.next();
            int rowNum = table.numRows();
            for (int j = 0; j < rowNum; j++) {
                row = table.getRow(j);
                int cellNum = row.numCells();
                for (int k = 0; k < cellNum; k++) {
                    cell = row.getCell(k);
                    String container = cell.text().trim();
                    if (container.indexOf("{{") != -1 && container.indexOf("}}") != -1) {
                        String s = parseString(container, map);
                        cell.replaceText(container, s);
                    }
                }
            }
        }
    }

    public static String parseString(String container, Map<String, Object> map) {
        if (container.indexOf("{{") != -1 && container.indexOf("}}") != -1) {
            String code = container.substring(container.indexOf("{{") + 2, container.indexOf("}}"));
            if (map.containsKey(code)) {
                String s = StringUtils.replace(container, "{{" + code + "}}", map.get(code).toString());
                return parseString(s, map);
            }
        }
        return container;
    }

最后说一点、部署到linux的时候记得在指定路径下存放word模板,别忘了不然会报错。
这个util亲测可用,有问题可以在评论里说,或者联系QQ:857957495。

你可能感兴趣的:(随笔)