Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用Apache POI XWPF中的多个单词替换文本不起作用-org.Apache.xmlbeans.impl.values.XmlValueDisconnectedException_Java_Ms Word_Apache Poi_Xwpf - Fatal编程技术网

Java 用Apache POI XWPF中的多个单词替换文本不起作用-org.Apache.xmlbeans.impl.values.XmlValueDisconnectedException

Java 用Apache POI XWPF中的多个单词替换文本不起作用-org.Apache.xmlbeans.impl.values.XmlValueDisconnectedException,java,ms-word,apache-poi,xwpf,Java,Ms Word,Apache Poi,Xwpf,使用下面@Thierry Bodhuin提供的示例,尝试将文本替换为段落中跨不同段落的多个单词,但是,它引发了以下异常: Exception in thread "main" org.apache.xmlbeans.impl.values.XmlValueDisconnectedException at org.apache.xmlbeans.impl.values.XmlObjectBase.check_orphaned(XmlObjectBase.java:1258) at org.open

使用下面@Thierry Bodhuin提供的示例,尝试将文本替换为段落中跨不同段落的多个单词,但是,它引发了以下异常:

Exception in thread "main" org.apache.xmlbeans.impl.values.XmlValueDisconnectedException
at org.apache.xmlbeans.impl.values.XmlObjectBase.check_orphaned(XmlObjectBase.java:1258)
at org.openxmlformats.schemas.wordprocessingml.x2006.main.impl.CTRImpl.isSetRsidDel(Unknown Source)
at org.apache.poi.xwpf.usermodel.XWPFParagraph.getText(XWPFParagraph.java:221)
at com.db.a.WordExtractReplaceFormat.replace(WordExtractReplaceFormat.java:60)
at com.db.a.WordExtractReplaceFormat.replace(WordExtractReplaceFormat.java:52)
at com.db.a.WordExtractReplaceFormat.replace(WordExtractReplaceFormat.java:37)
at com.db.a.WordExtractReplaceFormat.main(WordExtractReplaceFormat.java:114)
*此答案的代码片段[作者**Thierry Bodhuin

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class WordExtractReplaceFormat {

private static Map<Integer, XWPFRun> getPosToRuns(XWPFParagraph paragraph) {
    int pos = 0;
    Map<Integer, XWPFRun> map = new HashMap<Integer, XWPFRun>(10);
    for (XWPFRun run : paragraph.getRuns()) {
        String runText = run.text();
        if (runText != null) {
            for (int i = 0; i < runText.length(); i++) {
                map.put(pos + i, run);
            }
            pos += runText.length();
        }
    }
    return (map);
}

public static <V> void replace(XWPFDocument document, Map<String, V> map) throws FileNotFoundException, IOException {
    List<XWPFParagraph> paragraphs = document.getParagraphs();
    for (XWPFParagraph paragraph : paragraphs) {
        replace(paragraph, map);
    }
    String filePath = "C:\\test-1.docx";
    saveWord(filePath, document);
}

public static <V> void replace(XWPFDocument document, String searchText, V replacement) {
    List<XWPFParagraph> paragraphs = document.getParagraphs();
    for (XWPFParagraph paragraph : paragraphs) {
        replace(paragraph, searchText, replacement);
    }
}

private static <V> void replace(XWPFParagraph paragraph, Map<String, V> map) {
    for (Map.Entry<String, V> entry : map.entrySet()) {
        replace(paragraph, entry.getKey(), entry.getValue());
    }
}

public static <V> void replace(XWPFParagraph paragraph, String searchText, V replacement) {
    boolean found = true;
    while (found) {
        found = false;
        int pos = paragraph.getText().indexOf(searchText);
        if (pos >= 0) {
            found = true;
            Map<Integer, XWPFRun> posToRuns = getPosToRuns(paragraph);
            XWPFRun run = posToRuns.get(pos);
            XWPFRun lastRun = posToRuns.get(pos + searchText.length() - 1);
            int runNum = paragraph.getRuns().indexOf(run);
            int lastRunNum = paragraph.getRuns().indexOf(lastRun);
            String texts[] = replacement.toString().split("\n");
            run.setText(texts[0], 0);
            XWPFRun newRun = run;
            for (int i = 1; i < texts.length; i++) {
                newRun.addCarriageReturn();
                newRun = paragraph.insertNewRun(runNum + i);
                /*
                    We should copy all style attributes
                    to the newRun from run
                    also from background color, ...
                    Here we duplicate only the simple attributes...
                 */
                newRun.setText(texts[i]);
                newRun.setBold(run.isBold());
                newRun.setCapitalized(run.isCapitalized());
                // newRun.setCharacterSpacing(run.getCharacterSpacing());
                newRun.setColor(run.getColor());
                newRun.setDoubleStrikethrough(run.isDoubleStrikeThrough());
                newRun.setEmbossed(run.isEmbossed());
                newRun.setFontFamily(run.getFontFamily());
                newRun.setFontSize(run.getFontSize());
                newRun.setImprinted(run.isImprinted());
                newRun.setItalic(run.isItalic());
                newRun.setKerning(run.getKerning());
                newRun.setShadow(run.isShadowed());
                newRun.setSmallCaps(run.isSmallCaps());
                newRun.setStrikeThrough(run.isStrikeThrough());
                newRun.setSubscript(run.getSubscript());
                newRun.setUnderline(run.getUnderline());
            }
            for (int i = lastRunNum + texts.length - 1; i > runNum + texts.length - 1; i--) {
                paragraph.removeRun(i);
            }
        }
    }
}

public static void main(String[] args) throws FileNotFoundException, IOException {
    XWPFDocument docx;
    Map<String, String> keyValue = new TreeMap<>();
    keyValue.put("$<[Member] [Manager] [Officer]>", "Member Only");
    keyValue.put("${Lawyer_Name}", "Lawyer Name Updated with Actual");
    keyValue.put("${Place_Holder_Key}", "Place_Holder_value");

    WordExtractReplaceFormat wexrf = new WordExtractReplaceFormat();
    docx = new XWPFDocument(new FileInputStream("C:\\test.docx"));
    wexrf.replace(docx, keyValue);
}

private static void saveWord(String filePath, XWPFDocument doc) throws FileNotFoundException, IOException{
    FileOutputStream out = null;
    try{
        out = new FileOutputStream(filePath);
        doc.write(out);
    }
    finally{
        out.close();
    }
}
import java.io.FileInputStream;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Map;
导入java.util.TreeMap;
导入org.apache.poi.xwpf.usermodel.XWPFDocument;
导入org.apache.poi.xwpf.usermodel.XWPFParagraph;
导入org.apache.poi.xwpf.usermodel.XWPFRun;
公共类WordExtractReplaceFormat{
私有静态映射getPosToRuns(XWPFParagraph段落){
int pos=0;
Map Map=新的HashMap(10);
对于(XWPFRun:paragration.getRuns()){
字符串runText=run.text();
if(runText!=null){
对于(int i=0;i=0){
发现=真;
Map posToRuns=getPosToRuns(段落);
XWPFRun=posToRuns.get(pos);
XWPFRun lastRun=posToRuns.get(pos+searchText.length()-1);
int runNum=段落.getRuns().indexOf(run);
int lastRunNum=段落.getRuns().indexOf(lastRun);
字符串文本[]=replacement.toString().split(“\n”);
run.setText(文本[0],0);
XWPFRun newRun=run;
for(int i=1;irunNum+text.length-1;i--){
第1(i)段;
}
}
}
}
公共静态void main(字符串[]args)抛出FileNotFoundException、IOException{
xwpfdocx;
Map keyValue=newtreemap();
keyValue.put(“$”,“仅限成员”);
keyValue.put(“${Lawyer_Name}”,“用实际值更新的律师姓名”);
放置(${Place\u Holder\u Key}”,“Place\u Holder\u value”);
WordExtractReplaceFormat wexrf=新的WordExtractReplaceFormat();
docx=新的XWPFDocument(新文件输入流(“C:\\test.docx”);
wexrf.replace(docx,keyValue);
}
私有静态void保存字(字符串filePath,XWPFDocument doc)抛出FileNotFoundException,IOException{
FileOutputStream out=null;
试一试{
out=新的FileOutputStream(filePath);
写(出)文件;
}
最后{
out.close();
}
}
}


**代码在这一行失败-int pos=paragration.getText().indexOf(searchText);

我刚刚尝试了下面的代码,但不确定您的确切docx内容。 但正如我所观察到的,这种方法很有效

我想$docx文件中有。 这将替换所有内容,甚至替换每个经理成员等

 public class Find_Replace_DOCX {

        public static void main(String args[]) throws IOException,
                InvalidFormatException,
                org.apache.poi.openxml4j.exceptions.InvalidFormatException {
            try {

                /**
                 * if uploaded doc then use HWPF else if uploaded Docx file use
                 * XWPFDocument
                 */
                XWPFDocument doc = new XWPFDocument(
                        OPCPackage.open("d:\\1\\11.docx"));
                for (XWPFParagraph p : doc.getParagraphs()) {
                    List<XWPFRun> runs = p.getRuns();
                    if (runs != null) {
                        for (XWPFRun r : runs) {
                            String text = r.getText(0);
                            if (text != null
                                    && text.contains("$<[Member] [Manager] [Officer]>")) {
                                text = text.replace("Member", "new Member");
                                text = text.replace("Manager", "new manager");
                                text = text.replace("Officer", "new officer");
                                // text =
                                // text.replace("$<[Member] [Manager] [Officer]>",
                                // "new content");
                                r.setText(text, 0);
                            }
                        }
                    }
                }

                for (XWPFTable tbl : doc.getTables()) {
                    for (XWPFTableRow row : tbl.getRows()) {
                        for (XWPFTableCell cell : row.getTableCells()) {
                            for (XWPFParagraph p : cell.getParagraphs()) {
                                for (XWPFRun r : p.getRuns()) {
                                    String text = r.getText(0);
                                    if (text != null
                                            && text.contains("$<[Member] [Manager] [Officer]>")) {
                                        text = text.replace("Member", "new Member");
                                        text = text.replace("Manager",
                                                "new manager");
                                        text = text.replace("Officer",
                                                "new officer");
                                        // text =
                                        // text.replace("$<[Member] [Manager] [Officer]>",
                                        // "new content");
                                        r.setText(text, 0);
                                    }
                                }
                            }
                        }
                    }
                }

                doc.write(new FileOutputStream("d:\\1\\output.docx"));
            } finally {

            }

        }

    }
公共类查找\u替换\u DOCX{
公共静态void main(字符串args[])引发IOException,
无效格式异常,
org.apache.poi.openxml4j.exceptions.InvalidFormatException{
试一试{
/**
*如果上传文件,则使用HWPF;如果上传文件,则使用
*XWPFDocument
*/
XWPFDocument doc=新XWPFDocument(
OPCPackage.open(“d:\\1\\11.docx”);
对于(XWPFParagraph p:doc.getparagraph()){
List runs=p.getRuns();
如果(运行!=null){
用于(XWPFRun r:运行){