【问题标题】:How do I ADD bullet points to a word document using Apache POI in Java如何在 Java 中使用 Apache POI 向 word 文档添加项目符号
【发布时间】:2019-08-25 21:24:17
【问题描述】:

我有一个用作模板的 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);
                    });
                }

        }
    }

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

感谢您的帮助!


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


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

【问题讨论】:

  • 发生了什么?
  • 您希望所有字符串都在同一个单元格中,还是每个字符串在一个单元格中?当前输出是多少?
  • 感谢您的快速帮助。我用模板的一部分更新了问题。希望它会变得更清楚。
  • 如果您正在查看我的答案,您会看到 Minimal, Reproducible Example。我们需要您展示您正在使用的代码。请在我们可以下载的地方上传Word 模板。只有这样我们才能重现您的问题。
  • 阿克塞尔,我更新了代码。它仍然不是一个最小的、可重现的例子。如果你需要,我会在星期一尝试创建一个。我提供了模板的下载链接。希望有帮助。我仍然坚持这个编辑。非常感谢您的支持。

标签: java ms-word apache-poi


【解决方案1】:

由于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。在新插入或添加的段落中,其他项目被放置,编号和缩进设置取自占位符的段落。

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

【讨论】:

  • 嗨阿克塞尔,感谢您的快速回复。它有点工作。但是项目符号点是在第二个项目符号点之后添加的,并且样式不同。我用模板的图像更新了问题。
  • 哇!非常感谢阿克塞尔!非常感谢您的帮助!代码中有一些很好的技巧,帮助很大!
猜你喜欢
  • 1970-01-01
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
相关资源
最近更新 更多