我正在尝试编写一个将文本写入.docx文件的应用程序。我的应用程序使用JTextPane,因此用户可以编写他/她想要的任何内容,它还提供了许多按钮,如粗体,字体颜色,字体大小......等。我遇到的问题是在写入.docx文件时将JTextPane上的文本样式保留为。我对Swing和Apache POI相当新,所以示例代码和/或详细说明会有所帮助。
我拥有的是:( pad指的是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();
答案 0 :(得分:2)
对于我的示例,我假设您在HTMLEditorKit
中使用JTextPane
。然后我会解析窗格的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(), "<p>paragraph <b>1</b></p>", 0, 0, null);
kit.insertHTML(htmldoc, htmldoc.getLength(), "<p>paragraph <span style=\"color:red\">2</span></p>", 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();
}
}