Apache Poi - Java-:如何使用 Apache POI 将包含空行的文本作为单独的段落添加到 Word 文档中?

Apache Poi - Java-: How to add text containing blank lines as separate paragraphs to a Word document using Apache POI?

我无法将包含空行的文本作为单独的段落添加到 Word 文档中。

如果我尝试添加以下包含 3 个不同段落的文本。

  1. 这里有一些文字。
  2. 这里是另一个文本。
  3. 这里还有一个。

我得到的是 1. 这里有一些文字。 2. 这里是另一个文本。 3. 这里还有一个。好像他们是同一个段落。

是否可以使用 Apache POI 将包含空行的文本作为单独的段落添加到 Word 文档中?

    public static void addingMyParagraphs(XWPFDocument doc, String text) throws InvalidFormatException, IOException {

        XWPFParagraph p = doc.createParagraph();
        XWPFRun run = p.createRun();

        run.setText(text);
        run.setFontFamily("Times new Roman");
    }

--在下面的方法中,MyText 变量是一个 textArea 变量,它是 javaFx 应用程序的一部分。

    public void CreatingDocument() throws IOException, InvalidFormatException {
        String theText = myText.getText();
        addingMyParagraphs(doc, theText);

        FileOutputStream output = new FileOutputStream("MyDocument.docx");
        doc.write(output);
        output.close();
    }
}

您需要将您的文本拆分为“段落”并将每个段落分别添加到您的 WORD 文档中。这与JavaFX无关。

这里是一个使用 text blocks 模拟输入到 [JavaFX] TextArea 中的文本的示例。代码后的解释。

import java.io.FileOutputStream;
import java.io.IOException;

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

public class PoiWord0 {

    public static void main(String[] args) {
        String text = """
                1. Some text here.

                2. Another text here.
                
                3. Another one here.
                """;
        String[] paras = text.split("(?m)^[ \t]*\r?\n");
        try (XWPFDocument doc = new XWPFDocument();
             FileOutputStream output = new FileOutputStream("MyDocument.docx")) {
            for (String para : paras) {
                XWPFParagraph p = doc.createParagraph();
                XWPFRun run = p.createRun();
                run.setText(para.stripTrailing());
            }
            doc.write(output);
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}

我假设段落分隔符是一个空行,所以我在空行上拆分文本。这仍然在数组的每个元素中留下尾随换行符。我使用 stripTrailing() 删除换行符。

现在我有一个段落数组,所以我只需为每个数组元素向 [WORD] 文档添加一个新段落。

注意上面的代码是使用JDK15.

写的

用于拆分文本的正则表达式来自标题为 Remove empty line from a multi-line string with Java

的 SO 问题

try-with-resources 已添加到 Java 7.

stripTrailing() 已添加到 JDK 11