精华内容
下载资源
问答
  • word模板动态替换占位符(eg:${placeholder})然后生成新的word 网上搜索的不管是docx4j还是poi都只是实现了占位符在同一个文本中(读取word行数据后,行数据会分为多个文本)的替换,针对占位符没有在同一个文本...

    word模板动态替换占位符(eg:${placeholder})然后生成新的word

    网上搜索的不管是docx4j还是poi都只是实现了占位符在同一个文本中(读取word行数据后,行数据会分为多个文本)的替换,针对占位符没有在同一个文本或者换行了都没有实现,总结docx4j和poi两种方式终极实现占位符替换生成新word,两种方式源码如下

    1、Docx4J实现代码

    
    import cn.hutool.core.util.ObjectUtil;
    import com.google.common.collect.Lists;
    import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
    import org.docx4j.wml.ContentAccessor;
    import org.docx4j.wml.Text;
    import org.junit.Test;
    
    import javax.xml.bind.JAXBElement;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * @author liuchao
     * @date 2020/6/8
     */
    public class Test01 {
    
        /**
         * 设置最大Text类型节点个数 如果超过此值,在删除占位符时可能会重复计算导致错误
         */
        private static int MAX_TEXT_SIZE = 1000000;
    
        @Test
        public void test() throws Exception {
            String docxFile = "/Users/liuchao/java/temp/1.docx";
            WordprocessingMLPackage template = WordprocessingMLPackage.load(new java.io.File(docxFile));
            List<Object> texts = getAllElementFromObject(
                    template.getMainDocumentPart(), Text.class);
            Map<String, String> map = new HashMap<>();
            map.put("${company}", "Company Name here...");
            map.put("${address}", "xxxfffadfasdf");
            map.put("${secondParty}", "xxxfffadfasdf");
            map.put("${year}", "xxxfffadfasdf");
            map.put("${month}", "xxxfffadfasdf");
            map.put("${day}", "xxxfffadfasdf");
            map.put("${money}", "1000");
            searchAndReplace(texts, map);
            template.save(new java.io.File("/Users/liuchao/java/temp/NEW.docx"));
        }
    
    
        /**
         * 递归获取所有的节点
         *
         * @param obj      当前文档
         * @param toSearch 要查询的节点类型
         * @return java.util.List<java.lang.Object>
         * @author liuchao
         * @date 2020/6/9
         */
        private static List<Object> getAllElementFromObject(Object obj,
                                                            Class<?> toSearch) {
            List<Object> result = Lists.newArrayListWithCapacity(60);
            if (obj instanceof JAXBElement) {
                obj = ((JAXBElement<?>) obj).getValue();
            }
            if (obj.getClass().equals(toSearch)) {
                result.add(obj);
            } else if (obj instanceof ContentAccessor) {
                List<?> children = ((ContentAccessor) obj).getContent();
                for (Object child : children) {
                    result.addAll(getAllElementFromObject(child, toSearch));
                }
            }
            return result;
        }
    
        /**
         * 查找并且替换占位符
         *
         * @param texts  当前文档所有的Text类型节点
         * @param values 要替换的占位符key\value
         * @return void
         * @author liuchao
         * @date 2020/6/9
         */
        public static void searchAndReplace(List<Object> texts, Map<String, String> values) {
            // 存储占位符 位置信息集合
            List<int[]> placeholderList = getPlaceholderList(texts, values);
            if (ObjectUtil.isEmpty(placeholderList)) {
                return;
            }
            int[] currentPlaceholder;
            // 删除元素占位符
            for (int i = 0; i < texts.size(); i++) {
                if (ObjectUtil.isEmpty(placeholderList)) {
                    break;
                }
                currentPlaceholder = placeholderList.get(0);
                Text textElement = (Text) texts.get(i);
                String v = textElement.getValue();
                StringBuilder nval = new StringBuilder();
                char[] textChars = v.toCharArray();
                for (int j = 0; j < textChars.length; j++) {
                    char c = textChars[j];
                    if (null == currentPlaceholder) {
                        nval.append(c);
                        continue;
                    }
                    // 计算是否需要排除当前节点
                    int start = currentPlaceholder[0] * MAX_TEXT_SIZE + currentPlaceholder[1];
                    int end = currentPlaceholder[2] * MAX_TEXT_SIZE + currentPlaceholder[3];
                    int cur = i * MAX_TEXT_SIZE + j;
                    // 排除'$'和'}'两个字符之间的字符
                    if (!(cur >= start && cur <= end)) {
                        nval.append(c);
                    }
    
                    if (j > currentPlaceholder[3] && i >= currentPlaceholder[2]) {
                        placeholderList.remove(0);
                        if (ObjectUtil.isEmpty(placeholderList)) {
                            currentPlaceholder = null;
                            continue;
                        }
                        currentPlaceholder = placeholderList.get(0);
                    }
                }
                textElement.setValue(nval.toString());
            }
        }
    
        /**
         * 获取占位符信息,并且在占位符后面填充值
         *
         * @param texts  Text类型节点集合
         * @param values 要替换的占位符key\value
         * @return java.util.List<int [ ]>
         * @author liuchao
         * @date 2020/6/9
         */
        public static List<int[]> getPlaceholderList(List<Object> texts, Map<String, String> values) {
            // 标识忽略
            int ignoreTg = 0;
            // 标识已读取到'$'字符
            int startTg = 1;
            // 标识已读取到'{'字符
            int readTg = 2;
            // 当前标识
            int modeTg = ignoreTg;
    
            // 存储占位符 位置信息集合
            List<int[]> placeholderList = new ArrayList<>();
            // 当前占位符 0:'$'字符Text在texts中下标
            //          1:'$'字符在Text.getValue().toCharArray()数组下标
            //          2: '}'字符Text在texts中下标
            //          3:'}'字符在Text.getValue().toCharArray()数组下标
            int[] currentPlaceholder = new int[4];
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < texts.size(); i++) {
                Text textElement = (Text) texts.get(i);
                String newVal = "";
                String text = textElement.getValue();
                StringBuilder textSofar = new StringBuilder();
                char[] textChars = text.toCharArray();
                for (int col = 0; col < textChars.length; col++) {
                    char c = textChars[col];
                    textSofar.append(c);
                    switch (c) {
                        case '$': {
                            modeTg = startTg;
                            sb.append(c);
                        }
                        break;
                        case '{': {
                            if (modeTg == startTg) {
                                sb.append(c);
                                modeTg = readTg;
                                currentPlaceholder[0] = i;
                                currentPlaceholder[1] = col - 1;
                            } else {
                                if (modeTg == readTg) {
                                    sb = new StringBuilder();
                                    modeTg = ignoreTg;
                                }
                            }
                        }
                        break;
                        case '}': {
                            if (modeTg == readTg) {
                                modeTg = ignoreTg;
                                sb.append(c);
                                newVal += textSofar.toString()
                                        + (null == values.get(sb.toString()) ? sb.toString() : values.get(sb.toString()));
                                textSofar = new StringBuilder();
                                currentPlaceholder[2] = i;
                                currentPlaceholder[3] = col;
                                placeholderList.add(currentPlaceholder);
                                currentPlaceholder = new int[4];
                                sb = new StringBuilder();
                            } else if (modeTg == startTg) {
                                modeTg = ignoreTg;
                                sb = new StringBuilder();
                            }
                        }
                        default: {
                            if (modeTg == readTg) {
                                sb.append(c);
                            } else if (modeTg == startTg) {
                                modeTg = ignoreTg;
                                sb = new StringBuilder();
                            }
                        }
                    }
                }
                newVal += textSofar.toString();
                textElement.setValue(newVal);
            }
            return placeholderList;
        }
    

    依赖jar

            <dependency>
                <groupId>org.docx4j</groupId>
                <artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
                <version>8.1.7</version>
            </dependency>
            <!--hutool工具类-->
            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>4.6.0</version>
            </dependency>
            <!--json格式化-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.60</version>
            </dependency>  

     

    2、Poi实现代码

    
    import cn.hutool.core.io.FileUtil;
    import cn.hutool.core.util.ObjectUtil;
    import org.apache.poi.xwpf.usermodel.XWPFDocument;
    import org.apache.poi.xwpf.usermodel.XWPFParagraph;
    import org.apache.poi.xwpf.usermodel.XWPFRun;
    import org.junit.Test;
    
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * @author liuchao
     * @date 2020/6/9
     */
    public class Test03 {
    
        // 标识忽略
        static final int ignoreTg = 0;
        // 标识已读取到'$'字符
        static final int startTg = 1;
        // 标识已读取到'{'字符
        static final int readTg = 2;
    
        @Test
        public void test() throws Exception {
            Map<String, String> map = new HashMap<>();
            map.put("${company}", "Company Name here...");
            map.put("${address}", "xxxfffadfasdf");
            map.put("${secondParty}", "xxxfffadfasdf");
            map.put("${year}", "xxxfffadfasdf");
            map.put("${month}", "xxxfffadfasdf");
            map.put("${day}", "xxxfffadfasdf");
            map.put("${money}", "1000");
    
            XWPFDocument doc = new XWPFDocument(new FileInputStream(new File("/Users/liuchao/java/temp/1.docx")));
            List<XWPFParagraph> paragraphList = Lists.newArrayList(doc.getParagraphs());
            // 获取表格中的占位符信息
            getTableParagraphs(doc, paragraphList, placeholderValues);
            //获取占位符,并且将占位符需要替换的值写入
            List<int[]> placeholderList = getPlaceholderList(paragraphList, map);
            //清除占位符信息
            clearPlaceholder(placeholderList, paragraphList);
            BufferedOutputStream bos = FileUtil.getOutputStream(new File("/Users/liuchao/java/temp/NEW.docx"));
            doc.write(bos);
            bos.flush();
            bos.close();
            doc.close();
        }
    
    
        /**
         * 获取表格中占位符信息
         *
         * @param doc               当前文档
         * @param list              存储占位符信息
         * @param placeholderValues 需要替换的值
         * @return void
         * @author liuchao
         * @date 2020/7/6
         */
        private void getTableParagraphs(XWPFDocument doc, List<XWPFParagraph> list, Map<String, String> placeholderValues) {
            List<XWPFTable> tables = doc.getTables();
            if (ObjectUtil.isEmpty(tables)) {
                return;
            }
            tables.forEach(table -> table.getRows().forEach(row -> row.getTableCells().forEach(cell -> {
                String text = cell.getText();
                if (ObjectUtil.isEmpty(text)) {
                    return;
                }
                Iterator<String> it = placeholderValues.keySet().iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    if (text.indexOf(key) != -1) {
                        list.addAll(cell.getParagraphs());
                    }
                }
            })));
        }
    
    
    
        /**
         * 清除占位符信息
         *
         * @param placeholderList 占位符位置信息
         * @param paragraphList   行数据
         * @return void
         * @author liuchao
         * @date 2020/6/10
         */
        public static void clearPlaceholder(List<int[]> placeholderList, List<XWPFParagraph> paragraphList) {
            if (ObjectUtil.isEmpty(placeholderList)) {
                return;
            }
            int[] currentPlaceholder = placeholderList.get(0);
            StringBuilder tempSb = new StringBuilder();
            for (int i = 0; i < paragraphList.size(); i++) {
                XWPFParagraph p = paragraphList.get(i);
                List<XWPFRun> runs = p.getRuns();
                for (int j = 0; j < runs.size(); j++) {
                    XWPFRun run = runs.get(j);
                    String text = run.getText(run.getTextPosition());
                    StringBuilder nval = new StringBuilder();
                    char[] textChars = text.toCharArray();
                    for (int m = 0; m < textChars.length; m++) {
                        char c = textChars[m];
                        if (null == currentPlaceholder) {
                            nval.append(c);
                            continue;
                        }
                        // 排除'$'和'}'两个字符之间的字符
                        int start = currentPlaceholder[0] * 1000000 + currentPlaceholder[1] * 500 + currentPlaceholder[2];
                        int end = currentPlaceholder[3] * 1000000 + currentPlaceholder[4] * 500 + currentPlaceholder[5];
                        int cur = i * 1000000 + j * 500 + m;
                        if (!(cur >= start && cur <= end)) {
                            nval.append(c);
                        } else {
                            tempSb.append(c);
                        }
                        //判断是否是占位符结尾,如果是那获取新的占位符
                        if (tempSb.toString().endsWith("}")) {
                            placeholderList.remove(0);
                            if (ObjectUtil.isEmpty(placeholderList)) {
                                currentPlaceholder = null;
                                continue;
                            }
                            currentPlaceholder = placeholderList.get(0);
                            tempSb = new StringBuilder();
                        }
                    }
                    run.setText(nval.toString(), run.getTextPosition());
    
                }
            }
        }
    
        /**
         * 获取占位符信息,并且在占位符后面填充值
         *
         * @param paragraphList 行数据
         * @param map           要替换的占位符key\value
         * @return java.util.List<int [ ]>
         * @author liuchao
         * @date 2020/6/10
         */
        public static List<int[]> getPlaceholderList(List<XWPFParagraph> paragraphList, Map<String, String> map) {
            // 存储占位符 位置信息集合
            List<int[]> placeholderList = new ArrayList<>();
            // 当前占位符 0:'$'字符在XWPFParagraph集合中下标
            //          1:'$'字符在XWPFRun集合中下标
            //          2:'$'字符在text.toCharArray()数组下标
            //          3: '}'字符在XWPFParagraph集合中下标
            //          4: '}'字符在XWPFRun集合中下标
            //          5:'}'字符在text.toCharArray()数组下标
            int[] currentPlaceholder = new int[6];
    
            // 当前标识
            int modeTg = ignoreTg;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < paragraphList.size(); i++) {
                XWPFParagraph p = paragraphList.get(i);
                List<XWPFRun> runs = p.getRuns();
                for (int j = 0; j < runs.size(); j++) {
                    XWPFRun run = runs.get(j);
                    String text = run.getText(run.getTextPosition());
                    char[] textChars = text.toCharArray();
                    String newVal = "";
                    StringBuilder textSofar = new StringBuilder();
                    for (int m = 0; m < textChars.length; m++) {
                        char c = textChars[m];
                        textSofar.append(c);
                        switch (c) {
                            case '$': {
                                modeTg = startTg;
                                sb.append(c);
                            }
                            break;
                            case '{': {
                                if (modeTg == startTg) {
                                    sb.append(c);
                                    modeTg = readTg;
                                    currentPlaceholder[0] = i;
                                    currentPlaceholder[1] = j;
                                    currentPlaceholder[2] = m - 1;
                                } else {
                                    if (modeTg == readTg) {
                                        sb = new StringBuilder();
                                        modeTg = ignoreTg;
                                    }
                                }
                            }
                            break;
                            case '}': {
                                if (modeTg == readTg) {
                                    modeTg = ignoreTg;
                                    sb.append(c);
                                    String val = map.get(sb.toString());
                                    if (ObjectUtil.isNotEmpty(val)) {
                                        newVal += textSofar.toString() + val;
                                        placeholderList.add(currentPlaceholder);
                                        textSofar = new StringBuilder();
                                    }
                                    currentPlaceholder[3] = i;
                                    currentPlaceholder[4] = j;
                                    currentPlaceholder[5] = m;
                                    currentPlaceholder = new int[6];
                                    sb = new StringBuilder();
                                } else if (modeTg == startTg) {
                                    modeTg = ignoreTg;
                                    sb = new StringBuilder();
                                }
                            }
                            default: {
                                if (modeTg == readTg) {
                                    sb.append(c);
                                } else if (modeTg == startTg) {
                                    modeTg = ignoreTg;
                                    sb = new StringBuilder();
                                }
                            }
                        }
                    }
                    newVal += textSofar.toString();
                    run.setTextPosition(0);
                    run.setText(newVal, run.getTextPosition());
                }
            }
            return placeholderList;
        }

    依赖jar

                <!--hutool工具类-->
                <dependency>
                    <groupId>cn.hutool</groupId>
                    <artifactId>hutool-all</artifactId>
                    <version>4.6.0</version>
                </dependency>
                <!--json格式化-->
                <dependency>
                    <groupId>com.alibaba</groupId>
                    <artifactId>fastjson</artifactId>
                    <version>1.2.60</version>
                </dependency>  
                <dependency>
                    <groupId>org.apache.poi</groupId>
                    <artifactId>poi</artifactId>
                    <version>4.1.1</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.poi</groupId>
                    <artifactId>poi-ooxml</artifactId>
                    <version>4.1.1</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.poi</groupId>
                    <artifactId>poi-ooxml-schemas</artifactId>
                    <version>4.1.1</version>
                </dependency>                      

     

     

    展开全文
  • import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import j...

    package cn.action;

    import java.io.File;

    import java.io.FileInputStream;

    import java.io.FileNotFoundException;

    import java.io.FileOutputStream;

    import java.io.IOException;

    import java.io.InputStream;

    import java.util.ArrayList;

    import java.util.Date;

    import java.util.HashMap;

    import java.util.Iterator;

    import java.util.List;

    import java.util.Map;

    import java.util.Set;

    import javax.xml.parsers.DocumentBuilder;

    import javax.xml.parsers.DocumentBuilderFactory;

    import javax.xml.transform.Transformer;

    import javax.xml.transform.TransformerFactory;

    import javax.xml.transform.dom.DOMSource;

    import javax.xml.transform.stream.StreamResult;

    import org.w3c.dom.Document;

    import org.w3c.dom.Element;

    import org.w3c.dom.NodeList;

    import sun.misc.BASE64Encoder;

    public class XmlWord {

    private MapdataMap = new HashMap();

    public MapgetDataMap() {

    return dataMap;

    }

    public void setDataMap(MapdataMap) {

    this.dataMap = dataMap;

    }

    /**

    * 设置标识值

    * @param tagList 标识

    * @param dataList 数据

    * @param dataMap

    */

    public void setData(ListtagList,ListdataList){

    展开全文
  • 以前写过用asposeword 替换文字和图片,但是后来遇到问题,有些word替换替换图片后会导致打开时弹出错误:此文件中检测到错误,单word可以通过进行一下修复来打开文件。 考虑可能是版本有bug,于是从官网下了最新的...

    以前写过用asposeword 替换文字和图片,但是后来遇到问题,有些word替换替换图片后会导致打开时弹出错误:此文件中检测到错误,单word可以通过进行一下修复来打开文件。

    考虑可能是版本有bug,于是从官网下了最新的20.7版本。

    下载:aspose word for java 20.7

    新版替换字符为图片的方法有些不一样

    使用方法:

    package xf.test;
    
    import com.aspose.words.*;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    
    public class TestAspose {
        public static void main(String[] args) {
            try {
    
                 //doc 和docx 都是可以的
                Map<String,String>pmap = new HashMap<String,String>();
                pmap.put("[编写签名区域]","$pic:D:/javatest/sign2.png");
                pmap.put("$编号$","BH12345");
                //replace("D:/javatest/test删除图片.doc","D:/javatest/aspose测试删除图片.doc",pmap);
    //            replace("D:/javatest/田湾核电一期_机发变组定值清单A58.docx","D:/javatest/aspose测试删除图片.docx",pmap);
                replace("D:/javatest/aspose测试删除图片.docx","D:/javatest/aspose测试删除图片2.docx",pmap);
    
        }catch (Exception e){
            e.printStackTrace();
        }
        }
    
    
    
        public static boolean replace(String path, String outPath, Map<String,String> paramMap){
            if(path == null || path.isEmpty()) return false;
            if(outPath == null || outPath.isEmpty()) return false;
            if(paramMap == null || paramMap.isEmpty()) return false;
            try {
                Document doc = new Document(path);
                Iterator<String> paramKey = paramMap.keySet().iterator();
                while(paramKey.hasNext()){
                    String key = paramKey.next();
                    String v = paramMap.get(key);
                    if(v.startsWith("$pic:")){
                        v = v.substring(5);
                        //如果key已经被替换成图片了,那就要将图片替换成新的图片,相当于重新插入图片
                        NodeCollection shapeCollection = doc.getChildNodes(NodeType.SHAPE, true);
                        Iterator<Shape>  shapeIterate =  shapeCollection.iterator();
                        java.util.List<Shape> shaplist = new ArrayList<Shape>();
                        while(shapeIterate.hasNext()){
                            Shape shape = shapeIterate.next();
                            if(key.equals(shape.getName())){
                                shaplist.add(shape);
                            }
                        }
                        DocumentBuilder builder = new DocumentBuilder(doc);
                        for(int i=0;i<shaplist.size();i++){
                            Shape shape = shaplist.get(i);
                            //将光标移动到指定节点
                            builder.moveTo(shape);
                            Shape img = builder.insertImage(v);
                            img.setName(key);
                            System.out.println("replace" +key);
                            shape.remove();
                        }
                        //替换文字为图片
                        doc.getRange().replace(key, "", new FindReplaceOptions(new ReplaceAndInsertImage(v,key)));
                    }else{
                        doc.getRange().replace(key,v);
                    }
                }
                doc.save(outPath);
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
            return true;
        }
    }
    
    
    class ReplaceAndInsertImage implements IReplacingCallback {
        private String url;
        private String name;
        public ReplaceAndInsertImage(String url,String name){
            this.url = url;
            this.name = name;
        }
        @Override
        public int replacing(ReplacingArgs e) throws Exception {
            //获取当前节点
            Node currentNode = e.getMatchNode();
            //节点拆分处理当前匹配字段
            splitRun(currentNode,e.getMatchOffset());
            //获取当前文档
            Document document =  (Document) currentNode.getDocument();
            DocumentBuilder builder = new DocumentBuilder(document);
            //将光标移动到指定节点
            builder.moveTo(currentNode);
            //插入图片
            Shape img = builder.insertImage(url);
            img.setName(name);
            return ReplaceAction.SKIP;
        }
        private void splitRun(Node currentNode ,int position){
            String text =  currentNode.getText();
            Node newNode = currentNode.deepClone(true);
            if(text.length() >= position+this.name.length()){
                ((Run)currentNode).setText (text.substring(position+this.name.length()));
            }else{
                int morlength = position+this.name.length() - text.length();
                ((Run)currentNode).setText ("");
                Node tmpnode = currentNode;
                for(int i=0;i<this.name.length();i++){
                    System.out.println(i);
                    tmpnode = tmpnode.getNextSibling();
                    String tmptext= tmpnode.getText();
                    System.out.println(tmptext);
                    System.out.println(morlength);
                    System.out.println("--------"+(tmptext.length() >= morlength));
    
                    if(tmptext.length() >= morlength){
                        ((Run)tmpnode).setText(tmptext.substring(morlength));
                        break;
                    }else{
                        morlength = morlength - tmptext.length();
                        ((Run)tmpnode).setText("");
                    }
                }
            }
            if(position>0){
                ((Run)newNode).setText(text.substring(0, position));
                currentNode.getParentNode().insertBefore(newNode, currentNode);
            }
        }
    }
    

    20200813更新:原方法处理doc时存在bug,替换占位符为图片后,图片不是在占位符所在的位置,而是在占位符所在的node的起始位置,增加splitRun方法分割node节点。

     

    展开全文
  • 1.占位符替换模板导出(只适用于word中含有表格形式的):/// /// 使用替换模板进行到处word文件/// public class WordUtility{private object tempFile = null;private object saveFile = null;private static Word._...

    1.占位符替换模板导出(只适用于word中含有表格形式的):

    ///

    /// 使用替换模板进行到处word文件

    ///

    public class WordUtility

    {

    private object tempFile = null;

    private object saveFile = null;

    private static Word._Document wDoc = null; //word文档

    private static Word._Application wApp = null; //word进程

    private object missing = System.Reflection.Missing.Value;

    public WordUtility(string tempFile, string saveFile)

    {

    tempFile = System.Web.HttpContext.Current.Server.MapPath(tempFile);

    saveFile = System.Web.HttpContext.Current.Server.MapPath(saveFile);

    this.tempFile = tempFile;// Path.Combine(Application.StartupPath, @tempFile);

    this.saveFile = saveFile;// Path.Combine(Application.StartupPath, @saveFile);

    }

    ///

    /// 模版包含头部信息和表格,表格重复使用

    ///

    /// 重复表格的数据

    /// word中要替换的表达式和表格字段的对应关系

    /// 简单的非重复型数据

    public bool GenerateWord(DataTable dt, Dictionary expPairColumn, Dictionary simpleExpPairValue)

    {

    if (!File.Exists(tempFile.ToString()))

    {

    return false;

    }

    try

    {

    wApp = new Word.Application();

    wApp.Visible = false;

    wDoc = wApp.Documents.Add(ref tempFile, ref missing, ref missing, ref missing);

    wDoc.Activate();// 当前文档置前

    bool isGenerate = false;

    if (simpleExpPairValue != null && simpleExpPairValue.Count > 0)

    isGenerate = ReplaceAllRang(simpleExpPairValue);

    // 表格有重复

    if (dt != null && dt.Rows.Count > 0 && expPairColumn != null && expPairColumn.Count > 0)

    isGenerate = GenerateTable(dt, expPairColumn);

    if (isGenerate)

    wDoc.SaveAs(ref saveFile, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,

    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

    DisposeWord();

    return true;

    }

    catch (Exception ex)

    {

    return false;

    }

    }

    ///

    /// 单个替换 模版没有重复使用的表格

    ///

    /// 要替换的

    public bool GenerateWord(Dictionary dc)

    {

    return GenerateWord(null, null, dc);

    }

    private bool GenerateTable(DataTable dt, Dictionary expPairColumn)

    {

    try

    {

    int tableNums = dt.Rows.Count;

    for (int j = 1; j <= wDoc.Tables.Count; j++)

    {

    Word.Table tb = wDoc.Tables[j];

    tb.Range.Copy();

    Dictionary dc = new Dictionary();

    for (int i = 0; i < tableNums; i++)

    {

    dc.Clear();

    if (i == 0)

    {

    foreach (string key in expPairColumn.Keys)

    {

    string column = expPairColumn[key];

    object value = null;

    value = dt.Rows[i][column];

    dc.Add(key, value);

    }

    ReplaceTableRang(wDoc.Tables[j], dc);

    continue;

    }

    wDoc.Paragraphs.Last.Range.Paste();

    foreach (string key in expPairColumn.Keys)

    {

    string column = expPairColumn[key];

    object value = null;

    value = dt.Rows[i][column];

    dc.Add(key, value);

    }

    ReplaceTableRang(wDoc.Tables[j], dc);

    }

    }

    return true;

    }

    catch (Exception ex)

    {

    DisposeWord();

    return false;

    }

    }

    private bool ReplaceTableRang(Word.Table table, Dictionary dc)

    {

    try

    {

    object replaceArea = Word.WdReplace.wdReplaceAll;

    foreach (string item in dc.Keys)

    {

    object replaceKey = item;

    object replaceValue = dc[item];

    table.Range.Find.Execute(ref replaceKey, ref missing, ref missing, ref missing,

    ref missing, ref missing, ref missing, ref missing, ref missing,

    ref replaceValue, ref replaceArea, ref missing, ref missing, ref missing,

    ref missing);

    }

    return true;

    }

    catch (Exception ex)

    {

    DisposeWord();

    return false;

    }

    }

    private bool ReplaceAllRang(Dictionary dc)

    {

    try

    {

    object replaceArea = Word.WdReplace.wdReplaceAll;

    foreach (string item in dc.Keys)

    {

    object replaceKey = item;

    object replaceValue = dc[item];

    wApp.Selection.Find.Execute(ref replaceKey, ref missing, ref missing, ref missing,

    ref missing, ref missing, ref missing, ref missing, ref missing,

    ref replaceValue, ref replaceArea, ref missing, ref missing, ref missing,

    ref missing);

    }

    return true;

    }

    catch (Exception ex)

    {

    return false;

    }

    }

    private void DisposeWord()

    {

    object saveOption = Word.WdSaveOptions.wdSaveChanges;

    wDoc.Close(ref saveOption, ref missing, ref missing);

    saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;

    wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程

    }

    }

    demo:

    #region 动态创建DataTable数据

    DataTable tblDatas = new DataTable("Datas");

    DataColumn dc = null;

    //赋值给dc,是便于对每一个datacolumn的操作

    dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));

    dc.AutoIncrement = true;//自动增加

    dc.AutoIncrementSeed = 1;//起始为1

    dc.AutoIncrementStep = 1;//步长为1

    dc.AllowDBNull = false;//

    dc = tblDatas.Columns.Add("NO", Type.GetType("System.String"));//1

    DataRow newRow;

    newRow = tblDatas.NewRow();

    newRow["NO"] = info.NO;房屋座落地址 2--info实体类

    tblDatas.Rows.Add(newRow);

    #endregion

    #region word要替换的表达式和表格字段的对应关系

    Dictionary dic = new Dictionary();

    dic.Add("$id$", "NO");//3

    #endregion

    string tempFile = "~/Doc/doc.doc";

    string saveFile = "~/Doc/" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".doc";

    WordUtility w = new WordUtility(tempFile, saveFile);

    w.GenerateWord(tblDatas, dic, null);

    展开全文
  • 1.java处理word是个大大的坑,无论是poi还是Java2word 都不是尽善尽美。2.poi只能进行简单读操作,Java2word需要调用系统的com接口,系统机必须安装office和动态链接库。3.word从2003版本就可以保存为xml格式,通过...
  • 1.java处理word是个大大的坑,无论是poi还是Java2word 都不是尽善尽美。 2.poi只能进行简单读操作,Java2word需要调用系统的com接口,系统机必须安装office和动态链接库。 3.word从2003版本就可以保存为xml格式,...
  • doc类型的word用HWPFDocument类进行解析 docx类型的word用XWPFDocument类进行解析 /** * * @param srcPath word模板数据源路径 * @param destPath word导出路径 * @param map 关键字键值对映射 * @...
  • 公司做的项目要用到文本上传功能。 网上找了很久,大部分都有一些不成熟的问题,...%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%><%@ pagecontentType="text/html;charset=utf-8"%>...
  • 1、制作模板先用office word做一个模板word文档,${usrName}、${nowDate}占位符 可以使用 office 或者 wps 先创建一个模板表格 (替换$部分可以在 模板格式改变之后 在替换xml 格式改了后有些原本的字符会分开)2、...
  • 其原理就是先做一个word模板, 该模板中变量数据用xxx这种方式填写,然后再导出时只需读取模板然后用相应的数据替换其中的{xxx}这种方式填写, 然后再导出时只需读取模板然后用相应的数据替换其中的xxx这种方式填写,...
  • 这里以这个文件为例,在要替换的地方用占位符 $replaceXX@ 替换。 第二步:将word文件另存为.xml格式 第三步:放到idea中的一个目录下 这里已src目录为例 第四步:修改占位符 第五步:代码示例 package ...
  • 1、制作模板先用office word做一个模板word文档,${usrName}、${nowDate}占位符 可以使用 office 或者 wps 先创建一个模板表格 (替换$部分可以在 模板格式改变之后 在替换xml 格式改了后有些原本的字符会分开)2、...
  • 先把word文件另存为xml,在xml文件中插入特殊的字符串占位符,将xml翻译为FreeMarker模板,最后用java来解析FreeMarker模板,编码调用FreeMarker实现文本替换并输出Doc。优点:比Java2word功能强大,也是纯Java编程...
  • 我确实有几个Word模板,我的要求是使用Java根据用户输入替换文档中的一些单词/占位符.我尝试了很多库,包括2-3个版本的docx4j,但没有什么工作,他们都没有做任何事情!我知道之前已经问过这个问题,但我尝试了所有我知道...
  • ** Freemarker java导出word文档 ...然后搜索在word里填充的占位符。然后替换成后面能被替换的格式。比如,把Tb111,替换成${tb111}。这里可能原始的占位符发生了截断,比如本来是Tb111,但是在ftl模版里
  • Java自动生成带图片、富文本、表格等的word文档使用技术freemark+jsoup生成mht格式的伪word文档,已经应用...使用freemark替换模板的占位符,将变量以及图片资源放入模板中在输出文件maven地址org.freemarkerfreem...
  • 实现方式,定义一份word文档模板,使用占位符方式来替换文本内容。 问题,怎么实现word文档合并?,及兼容图片? 这里稍微剖析下原理:上面合并的原理是,将word文档转换为xml字符串,然后把要合并的文档的xml进行...
  • java运用poi操作word,替换word中的占位符填充数据,并将多个word合并成一个word,附件是java代码和相关jar包,以及测试模板,需要注意是,只适用2007以上的word
  • java word导出pdf

    2019-11-01 11:42:00
    整体思路就是: 使用word模板引擎,将占位符(格式:{{title}})替换为查询出来的数据,再将替换完成的word转换为pdf doc转pdf源码: https://gitee.com/java_long/docs-to-pdf-converter.git word模板引擎: ht...
  • 就能够将Office文档转换成XML文件,这样仅仅要将须要填入的内容放上${}占位符,就能够使用像Freemarker这种模板引擎将出现占位符的地方替换成真实数据,这种方式较之其它的方案要更为简单。以...
  • 模板把word中的占位符替换为实际的值,注意WPFRun表示有相同属性的一段文本,所以模板里变量内容需要从左到右的顺序写,${name},如果先写${},再添加内容,会拆分成几部分,不能正常使用,因此若出现替换失败的...
  • 第一步就是先建一个world文档,然后将World文档里面需要从数据库或者其他方式想要填充的部分用占位符替换 第二步:就是将此文档选择xml文件格式保存 第三步:随便在eclipse中找个位置放下,并右键properties属性,...
  • Java Web项目中使用Freemarker生成Word文档

    万次阅读 多人点赞 2014-09-21 15:33:20
    基于Java的解决方案也是很多的,包括使用Jacob、Apache POI、Java2Word、iText等各种方式,其实在从Office 2003开始,就可以将Office文档转换成XML文件,这样只要将需要填入的内容放上${}占位符,就可以使用像...
  • [实用]【更新中】Java Apache POI 打印Word文档工具(含文本替换,动态表格功能)基于Apache POI对Word进行操作一、基于Apache POI封装的word文档工具V1.0介绍二、Apache POI 知识1. jar包(maven的,这个不多做解释...
  • 实现方式,定义一个word文档模板,使用字符串占位符替换文本内容,java后台引用模板实现导出 原理:生成一个word文档对象,获取其xml字段穿,多个word文档,将其xml字符串拼接。 package testModel; import ...
  • 一、创建word文档模板 生成想要生成的word样式,保存为xml...还有最重要的三个关键地方需要进行占位符替换 ① ② ③ 此处是将原文档加入的图片base64码进行占位符替换 至此,文档模板制作完成了 二、用poi导出文档
  • 我确实有几个Word模板,我的要求是使用Java根据用户输入替换文档中的一些单词/占位符.我尝试了很多库,包括2-3个版本的docx4j,但没有什么工作,他们都没有做任何事情!我知道之前已经问过这个问题,但我尝试了所有我知道...

空空如也

空空如也

1 2 3
收藏数 56
精华内容 22
关键字:

java替换word占位符

java 订阅