簡體   English   中英

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 無關。

這是一個使用文本塊模擬輸入到 [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] 文檔中添加一個新段落。

請注意,上述代碼是使用 JDK 15 編寫的。

用於拆分文本的正則表達式來自題為使用 Java 從多行字符串中刪除空行的 SO 問題

在 Java 7 中添加了try-with-resources

stripTrailing()是在 JDK 11 中添加的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM