java - 如何在 Java 中使用 Apache POI 将项目符号点添加到 word 文档

标签 java ms-word apache-poi

我有一个用作模板的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 结束。 使用字段会更容易吗?不过,我需要保持要点样式。

the word template


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

最佳答案

由于 Microsoft Word 在其存储中如何划分不同运行的文本方面非常非常“奇怪”,因此如果没有包括所有代码和 Word 文件有问题。拥有用于将内容添加到 Word 文档的通用代码似乎是不可能的,除非所有添加或替换仅在字段(表单字段或内容控件或邮件合并字段)中进行。

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

enter image description here

然后我运行了下面的代码:

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 如下所示:

enter image description here

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

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

关于java - 如何在 Java 中使用 Apache POI 将项目符号点添加到 word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57614276/

相关文章:

c# - COMException (0x800A13E9) - Word 互操作服务

C# 如何将自定义保存按钮添加到 Microsoft Word 中的 'Save As' 菜单

java - Excel 单元格中的多行文本

java - 如何使用 apache poi 在 docx 文件中设置普通标题?

java - 此应用程序不存在 (app_id=u'google.com :nbsocialmetrics')

java - 如何从对象数组列表中找到最大元素?

java - 空着 body 奔跑,永远奔跑

java - JMS消息监听器Weblogic的并发处理

c# - 如何使用 C# Windows 应用程序将 byte[] 中的图像写入 MS WORD

java - 如何为多个单元格 poi 添加不同的背景颜色