将样式文本写入.docx文件

我正在尝试编写一个将文本写入.docx文件的应用程序。 我的应用程序使用JTextPane,因此用户可以编写他/她想要的任何内容,它还提供了许多按钮,如粗体,字体颜色,字体大小……等。 我遇到的问题是在写入.docx文件时保持JTextPane上文本的样式。 我对Swing和Apache POI相当新,所以示例代码和/或详细说明会有所帮助。

我有这个:(垫指的是JTextPane)

FileOutputStream output = new FileOutputStream(file); XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(pad.getText()); document.write(output); output.close(); 

对于我的例子,我假设您在JTextPane使用了HTMLEditorKit 。 然后我将解析窗格的StyledDocument并相应地设置textruns。

当然这只是一个启动器,你需要解析所有可能的样式并在下面的循环中自己转换它们。

我承认,我从未对HTMLEditorKit做过什么,因此我不知道如何正确处理CSS.CssValues。

 import java.awt.Color; import java.io.FileOutputStream; import java.lang.reflect.Field; import java.util.Enumeration; import javax.swing.*; import javax.swing.text.*; import javax.swing.text.html.*; import org.apache.poi.xwpf.usermodel.*; public class StyledText { public static void main(String[] args) throws Exception { // prepare JTextPane pad = new JTextPane(); pad.setContentType("text/html"); HTMLEditorKit kit = (HTMLEditorKit)pad.getEditorKit(); HTMLDocument htmldoc = (HTMLDocument)kit.createDefaultDocument(); kit.insertHTML(htmldoc, htmldoc.getLength(), "

paragraph 1

", 0, 0, null); kit.insertHTML(htmldoc, htmldoc.getLength(), "

paragraph 2

", 0, 0, null); pad.setDocument(htmldoc); // convert StyledDocument doc = pad.getStyledDocument(); XWPFDocument docX = new XWPFDocument(); int lastPos=-1; while (lastPos < doc.getLength()) { Element line = doc.getParagraphElement(lastPos+1); lastPos = line.getEndOffset(); XWPFParagraph paragraph = docX.createParagraph(); for (int elIdx=0; elIdx < line.getElementCount(); elIdx++) { final Element frag = line.getElement(elIdx); XWPFRun run = paragraph.createRun(); String subtext = doc.getText(frag.getStartOffset(), frag.getEndOffset()-frag.getStartOffset()); run.setText(subtext); final AttributeSet as = frag.getAttributes(); final Enumeration ae = as.getAttributeNames(); while (ae.hasMoreElements()) { final Object attrib = ae.nextElement(); if (CSS.Attribute.COLOR.equals(attrib)) { // I don't know how to really work with the CSS-swing class ... Field f = as.getAttribute(attrib).getClass().getDeclaredField("c"); f.setAccessible(true); Color c = (Color)f.get(as.getAttribute(attrib)); run.setColor(String.format("%1$02X%2$02X%3$02X", c.getRed(),c.getGreen(),c.getBlue())); } else if (CSS.Attribute.FONT_WEIGHT.equals(attrib)) { if ("bold".equals(as.getAttribute(attrib).toString())) { run.setBold(true); } } } } } FileOutputStream fos = new FileOutputStream("test.docx"); docX.write(fos); fos.close(); } }