java如何替换word中${}中的内容?

图片描述图片描述
在服务器上有一份模板合同,我需要点击不同的合同的时候,用该合同的内容填充到模板合同并下载
在模板合同中需要填充的内容都用${}代替了
请问如何实现呀?

图片描述
这些都要导入吗?还是只需要导入poi-3.17就可以了?
这几个需要导入哪个呀

阅读 15.8k
9 个回答

处理Word可以使用poi,
如何替换使用下面三个类就好了。

public class GenericTokenParser {

    private final String       openToken;
    private final String       closeToken;
    private final TokenHandler handler;

    public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
        this.openToken = openToken;
        this.closeToken = closeToken;
        this.handler = handler;
    }

    // 主要的逻辑就是取出expression,委托TokenHandler来替换expression。
    public String parse(String text) {
        if (text == null || text.isEmpty()) {
            return "";
        }
        // search open token
        int start = text.indexOf(openToken, 0);
        if (start == -1) {
            return text;
        }
        char[] src = text.toCharArray();
        int offset = 0;
        final StringBuilder builder = new StringBuilder();
        StringBuilder expression = null;
        while (start > -1) {
            if (start > 0 && src[start - 1] == '\\') {
                // this open token is escaped. remove the backslash and continue.
                builder.append(src, offset, start - offset - 1).append(openToken);
                offset = start + openToken.length();
            } else {
                // found open token. let's search close token.
                if (expression == null) {
                    expression = new StringBuilder();
                } else {
                    expression.setLength(0);
                }
                builder.append(src, offset, start - offset);
                offset = start + openToken.length();
                int end = text.indexOf(closeToken, offset);
                while (end > -1) {
                    if (end > offset && src[end - 1] == '\\') {
                        // this close token is escaped. remove the backslash and continue.
                        expression.append(src, offset, end - offset - 1).append(closeToken);
                        offset = end + closeToken.length();
                        end = text.indexOf(closeToken, offset);
                    } else {
                        expression.append(src, offset, end - offset);
                        offset = end + closeToken.length();
                        break;
                    }
                }
                if (end == -1) {
                    // close token was not found.
                    builder.append(src, start, src.length - start);
                    offset = src.length;
                } else {
                    builder.append(handler.handleToken(expression.toString()));
                    offset = end + closeToken.length();
                }
            }
            start = text.indexOf(openToken, offset);
        }
        if (offset < src.length) {
            builder.append(src, offset, src.length - offset);
        }
        return builder.toString();
    }
}
public class VariableTokenHandler implements TokenHandler {
        private final Properties variables;
        private final boolean    enableDefaultValue;
        private final String     defaultValueSeparator;

        public VariableTokenHandler(Properties variables) {
            this.variables = variables;
            this.enableDefaultValue = false;
            this.defaultValueSeparator = ":";
        }

        private String getPropertyValue(String key, String defaultValue) {
            return (variables == null) ? defaultValue : variables.getProperty(key, defaultValue);
        }

        @Override
        public String handleToken(String content) {
            if (variables != null) {
                String key = content;
                if (enableDefaultValue) {
                    final int separatorIndex = content.indexOf(defaultValueSeparator);
                    String defaultValue = null;
                    if (separatorIndex >= 0) {
                        key = content.substring(0, separatorIndex);
                        defaultValue = content.substring(separatorIndex + defaultValueSeparator.length());
                    }
                    if (defaultValue != null) { 
                        return variables.getProperty(key, defaultValue);
                    }
                }
                if (variables.containsKey(key)) {
                    return variables.getProperty(key);
                }
            }
            return "${" + content + "}"; 
        }
    }
public interface TokenHandler {
    String handleToken(String content);
}

使用方法:

public class Main {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put("name", "javaer");
        VariableTokenHandler tokenHandler = new VariableTokenHandler(properties);
        GenericTokenParser parser = new GenericTokenParser("${", "}", tokenHandler);
        String parse = parser.parse("my name is ${name}");
        System.out.println(parse);
    }
}

运行结果:
Screen Shot 2017-12-26 at 11.43.29
clipboard.png

正则表达式啊

Apache POI可以处理Word文档,文本替换用正则

同楼上 具体正则自行百度

XWPFTemplate template = XWPFTemplate.compile("~/file.docx").render(datas);

参见github项目:https://github.com/Sayi/poi-tl

  • {{template}}

普通文本,渲染数据为:String或者TextRenderData

  • {{@template}}

图片,渲染数据为:PictureRenderData

可以用freemarker实现,之前的一个项目,要生成word报告,最开始想用word模板编辑器,后来觉得复杂了,且效果不好。最后改成freemarker,效果不错,可以在模板中调成自己想要的内容格式,然后导出xml。
字符串替换用 ${string}
表格循环用标签

<#list  userList as user>
姓名:${user.userName},性别:${user.sex}
</#list>

可以直接用正则表达式来进行替换,可以试试看Spire.Doc for Java控件,它的代码操作简单,效果也很好。以下是相关代码示例,可以参考下。

import com.spire.doc.*;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) throws Exception {
        //加载示例文档
        Document document = new Document();
        document.loadFromFile("Sample.docx");

        //匹配以#开头,数字结尾的字符并用Spire.Doc替换
        Pattern c = Pattern.compile ("^#(.*?)\\d$");
        document.replace(c,"Spire.Doc");

        //匹配【】内的字符并用Spire.Doc for Java替换
        Pattern c2 = Pattern.compile("【[\\s\\S]*】");
        document.replace(c2, "Spire.Doc for Java");

        //保存文档
        document.saveToFile("Result.docx", FileFormat.Docx_2013);
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题