使用 POI 将 word 模板文档中的内容替换为 java

Replacing content in a word template document with java using POI

我需要打开一个.dotx文件,修改内容(或类似的东西)并放入我自己的数据,然后return生成.docx/document.

例如,在 dotx 文件中,字符串 "name" 应在生成的 docx 文件中替换为 "John"。

public static void main( String[] args ) throws IOException
{
    String inputFile="D:/Copies 2.dotx";
//  String outputeFile="D:/test.txt";
    String outputeFile="D:/test.docx";
    File inFile=new File(inputFile);
    File ouFile=new File(outputeFile);
    Map<String,String> hm = new HashMap<String,String>();
    hm.put("Namur","Youssef");
    App a = new App();
    a.changeData(inFile,ouFile, hm);    
}
private void changeData(File targetFile,File out, Map<String,String> substitutionData) throws IOException{
    BufferedReader br = null;
    String docxTemplate = "";
    try {
        br = new BufferedReader(new InputStreamReader(new FileInputStream(targetFile)));
        String temp;
        while( (temp = br.readLine()) != null) {
            docxTemplate = docxTemplate + temp;   
        }
        br.close();
    } 
    catch (IOException e) {
        br.close();
        throw e;
    }

    Iterator<Entry<String, String>> substitutionDataIterator = substitutionData.entrySet().iterator();
    while(substitutionDataIterator.hasNext()){
        Map.Entry<String,String> pair = (Map.Entry<String,String>)substitutionDataIterator.next();
        if(docxTemplate.contains(pair.getKey())){
            if(pair.getValue() != null)
                docxTemplate = docxTemplate.replace(pair.getKey(), pair.getValue());
            else
                docxTemplate = docxTemplate.replace(pair.getKey(), "NEDOSTAJE");
        }
    }

    FileOutputStream fos = null;
    try{
        fos = new FileOutputStream(out);
        fos.write(docxTemplate.getBytes());
        fos.close();
    }
    catch (IOException e) {
        fos.close();
        throw e;
    }

}

有人可以给我一些建议吗?

Ps: 我正在使用 apach POI 3.16

因为解析 dotx/docx 文件并不那么简单 我们有 apache poi 像

这样努力做到这一点
XWPFDocument doc = new XWPFDocument(OPCPackage.open("-you docx/dotx file-path-"));

有了它,您可以加载现有文件。 现在解析文件 你得到

XWPFParagraph
XWPFTable

你可以像这样解析两者

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("$$key$$")) {
                            text = text.replace("<asdas>", "ABCD");// your content
                            r.setText(text, 0);
                        }
                    }
                }
            }

解析 table

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("$$key$$")) {
                                    text = text.replace("<asdas>", "abcd");
                                    r.setText(text, 0);
                                }
                            }
                        }
                    }
                }
            }

现在将解析后的文件写入您获得的目标

doc.write(new FileOutputStream("-taget-path-"));

这需要与 apache POI 的所有依赖项 喜欢

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

您将需要在构建路径中添加更多内容,检查您的异常并添加。

您可以使用此 link 并探索更多内容

http://poi.apache.org/apidocs/dev/org/apache/poi/xwpf/usermodel/XWPFRun.html#setText%28java.lang.String%29