首页 > 解决方案 > 如何在 Java 中使用 Apache POI 向 word 文档添加项目符号

问题描述

我有一个用作模板的word文档。在这个模板中,我有一些包含预定义项目符号的表格。现在我试图用一组字符串替换占位符字符串。

我完全坚持这一点。我的简化方法如下所示。

        replaceKeyValue.put("[DescriptionOfItem]", new HashSet<>(Collections.singletonList("This is the description")));
        replaceKeyValue.put("[AllowedEntities]", new HashSet<>(Arrays.asList("a", "b")));
        replaceKeyValue.put("[OptionalEntities]", new HashSet<>(Arrays.asList("c", "d")));
        replaceKeyValue.put("[NotAllowedEntities]", new HashSet<>(Arrays.asList("e", "f")));

        try (XWPFDocument template = new XWPFDocument(OPCPackage.open(file))) {
            template.getTables().forEach(
                    xwpfTable -> xwpfTable.getRows().forEach(
                            xwpfTableRow -> xwpfTableRow.getTableCells().forEach(
                                    xwpfTableCell -> replaceInCell(replaceKeyValue, xwpfTableCell)
                            )
                    ));

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            template.write(baos);
            return new ByteArrayResource(baos.toByteArray());
        } finally {
            if (file.exists()) {
                file.delete();
            }
        }
private void replaceInCell(Map<String, Set<String>> replacementsKeyValuePairs, XWPFTableCell xwpfTableCell) {
        for (XWPFParagraph xwpfParagraph : xwpfTableCell.getParagraphs()) {
            for (Map.Entry<String, Set<String>> replPair : replacementsKeyValuePairs.entrySet()) {
                String keyToFind = replPair.getKey();
                Set<String> replacementStrings = replacementsKeyValuePairs.get(keyToFind);
                if (xwpfParagraph.getText().contains(keyToFind)) {
                    replacementStrings.forEach(replacementString -> {
                        XWPFParagraph paragraph = xwpfTableCell.addParagraph();
                        XWPFRun run = paragraph.createRun();
                        run.setText(replacementString);
                    });
                }

        }
    }

我期待在当前单元格中添加更多要点。我错过了什么吗?该段落是包含占位符字符串和格式的段落。

谢谢你的帮助!


更新:这就是模板的一部分。我想自动搜索这些术语并替换它们。搜索工作到目前为止。但是尝试替换项目符号点以 unlocatable 结尾NullPointer。使用字段会更容易吗?不过,我需要保持要点风格。

单词模板


更新 2:添加下载链接并更新代码。如果我正在遍历它们,似乎我无法更改这些段落。我得到一个空指针。下载链接:WordTemplate

标签: javams-wordapache-poi

解决方案


由于Microsoft Word它在存储中如何在不同运行中划分文本非常“奇怪”,因此如果没有包含所有代码和相关Word文档的完整示例,就无法回答此类问题。Word似乎不可能拥有用于向文档添加内容的通用代码,除非所有添加或替换仅在字段中(表单字段或内容控件或邮件合并字段)。

所以我下载了你的WordTemplate.docx,看起来像这样:

在此处输入图像描述

然后我运行以下代码:

import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;

import org.apache.xmlbeans.XmlCursor;

import java.util.*; 

import java.math.BigInteger;

public class WordReadAndRewrite {

 static void addItems(XWPFTableCell cell, XWPFParagraph paragraph, Set<String> items) {
  XmlCursor cursor = null;
  XWPFRun run = null;
  CTR cTR = null; // for a deep copy of the run's low level object

  BigInteger numID = paragraph.getNumID();
  int indentationLeft = paragraph.getIndentationLeft();
  int indentationHanging = paragraph.getIndentationHanging();

  boolean first = true;
  for (String item : items) {
   if (first) {
    for (int r = paragraph.getRuns().size()-1; r > 0; r--) {
     paragraph.removeRun(r);
    }
    run = (paragraph.getRuns().size() > 0)?paragraph.getRuns().get(0):null;
    if (run == null) run = paragraph.createRun();
    run.setText(item, 0);
    cTR = (CTR)run.getCTR().copy(); // take a deep copy of the run's low level object
    first = false;
   } else {
    cursor = paragraph.getCTP().newCursor();
    boolean thereWasParagraphAfter = cursor.toNextSibling(); // move cursor to next paragraph 
                                                             // because the new paragraph shall be **after** that paragraph
                                                             // thereWasParagraphAfter is true if there is a next paragraph, else false
    if (thereWasParagraphAfter) {
     paragraph = cell.insertNewParagraph(cursor); // insert new paragraph if there are next paragraphs in cell
    } else {
     paragraph = cell.addParagraph(); // add new paragraph if there are no other paragraphs present in cell
    }

    paragraph.setNumID(numID); // set template paragraph's numbering Id
    paragraph.setIndentationLeft(indentationLeft); // set template paragraph's indenting from left
    if (indentationHanging != -1) paragraph.setIndentationHanging(indentationHanging); // set template paragraph's hanging indenting
    run = paragraph.createRun();
    if (cTR != null) run.getCTR().set(cTR); // set template paragraph's run formatting
    run.setText(item, 0);
   }
  }
 }

 public static void main(String[] args) throws Exception {

  Map<String, Set<String>> replaceKeyValue = new HashMap<String, Set<String>>();
  replaceKeyValue.put("[AllowedEntities]", new HashSet<>(Arrays.asList("allowed 1", "allowed 2", "allowed 3")));
  replaceKeyValue.put("[OptionalEntities]", new HashSet<>(Arrays.asList("optional 1", "optional 2", "optional 3")));
  replaceKeyValue.put("[NotAllowedEntities]", new HashSet<>(Arrays.asList("not allowed 1", "not allowed 2", "not allowed 3")));

  XWPFDocument document = new XWPFDocument(new FileInputStream("WordTemplate.docx"));
  List<XWPFTable> tables = document.getTables();
  for (XWPFTable table : tables) {
   List<XWPFTableRow> rows = table.getRows();
   for (XWPFTableRow row : rows) {
    List<XWPFTableCell> cells = row.getTableCells();
    for (XWPFTableCell cell : cells) {

     int countParagraphs = cell.getParagraphs().size();
     for (int p = 0; p < countParagraphs; p++) { // do not for each since new paragraphs were added
      XWPFParagraph paragraph = cell.getParagraphArray(p);

      String placeholder = paragraph.getText();
      placeholder = placeholder.trim(); // this is the tricky part to get really the correct placeholder

      Set<String> items = replaceKeyValue.get(placeholder);
      if (items != null) {
       addItems(cell, paragraph, items);
      }
     }

    }
   }
  }

  FileOutputStream out = new FileOutputStream("Result.docx");
  document.write(out);
  out.close();
  document.close();

 }
}

Result.docx看起来像这样:

在此处输入图像描述

代码循环遍历Word文档中的表格单元格,并查找恰好包含占位符的段落。这甚至可能是棘手的部分,因为该占位符可能会被拆分为不同的文本Word。如果找到它会运行一个方法,该方法addItems将找到的段落作为编号和缩进的模板(尽管可能不完整)。然后它在找到的段落的第一个文本运行中设置第一个新项目,并删除可能存在的所有其他文本运行。然后它确定是否必须将新段落插入或添加到单元格中。为此XmlCursor,使用了 a。在新插入或添加的段落中,放置其他项目,编号和缩进设置取自占位符的段落。

如前所述,这是显示如何做的原则的代码。它必须扩展很多才能普遍使用。在我看来,那些在Word文档中使用文本占位符进行文本替换的试验并不是很好。文档中可变文本的占位符Word应该是字段。这可以是表单域、内容控件或邮件合并域。与文本占位符相比,字段的优势在于Word知道字段是可变文本的实体。它不会因为多种奇怪的原因将它们拆分为多个文本运行,就像它通常对普通文本所做的那样。


推荐阅读