Java 使用JTextPane样式选项创建Word文件

Java 使用JTextPane样式选项创建Word文件,java,ms-word,apache-poi,Java,Ms Word,Apache Poi,我想将JTextPane的内容保存到word文件中。 保存时没有问题,但当前无法保留某些样式选项,例如段落样式 我使用这些库: import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; 代码行 System.out.println("Kaydete bası

我想将JTextPane的内容保存到word文件中。 保存时没有问题,但当前无法保留某些样式选项,例如段落样式

我使用这些库:

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
代码行

System.out.println("Kaydete basıldı");
        String text = textPane.getText();
        lblNewLabel.setText(text);

        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText(text);

        try {

            FileOutputStream dosyaCikis = new FileOutputStream(
                    "sercan.docx");
            document.write(dosyaCikis);
            dosyaCikis.close();
        } catch (Exception e2) {
            e2.printStackTrace();
        }

ApachePOI或其他方式,没关系,我正在等待您的帮助。

AFAIK编写Word文件的选项仅限于标准Java库

您可能想使用一个明确支持Word格式的工具——最好的选择可能是LibreOffice,这是一款免费软件。支持Java和其他语言

要获得更全面的解释,请参见此处:


然而,这个答案是指OpenOffice,由于多年来的管理问题,LibreOffice是OpenOffice中一个更积极开发的分支。

这个例子展示了如何设置各种样式选项:(Apache POI)

链接中的示例代码:

   XWPFDocument doc = new XWPFDocument();
   XWPFParagraph p1 = doc.createParagraph();

        p1.setAlignment(ParagraphAlignment.CENTER);
        p1.setBorderBottom(Borders.DOUBLE);
        p1.setBorderTop(Borders.DOUBLE);    
        p1.setBorderRight(Borders.DOUBLE);
        p1.setBorderLeft(Borders.DOUBLE);
        p1.setBorderBetween(Borders.SINGLE);    
        p1.setVerticalAlignment(TextAlignment.TOP);

   XWPFRun r1 = p1.createRun();

        r1.setBold(true);
        r1.setText("The quick brown fox");
        r1.setBold(true);
        r1.setFontFamily("Courier");
        r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
        r1.setTextPosition(100);
其他示例(样式、图像等)可在此处找到:

你可以试试。从网页:

它可以打开docx文件并在JEditorPane(或 JTextPane)。用户还可以创建样式化内容并存储内容 以docx格式

有些相关的是我的,但它最近没有更新,它可能是过度为您的目的


两者都使用docx4j(与POI相反)。

您的问题令人困惑。你是想简单地从一个
JTextPane
复制文本,还是在Word文档中设计一个类似于
JTextPane
的样式?OP提到他正在使用Apache POI,它工作得很好。啊,是的,我错过了。很明显,我没有彻底阅读这个问题,尽管我认为进口可以更明确地表述——借口!(编辑:所以我改进了这个问题……编辑的力量!)