我稍加修改了您的代码,它复制文本而不更改文本格式。
public static void main(String[] args) { try { InputStream is = new FileInputStream("Japan.docx"); XWPFdocument doc = new XWPFdocument(is); List<XWPFParagraph> paras = doc.getParagraphs(); XWPFdocument newdoc = new XWPFdocument(); for (XWPFParagraph para : paras) { if (!para.getParagraphText().isEmpty()) { XWPFParagraph newpara = newdoc.createParagraph(); copyAllRunsToAnotherParagraph(para, newpara); } } FileOutputStream fos = new FileOutputStream(new File("newJapan.docx")); newdoc.write(fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}// Copy all runs from one paragraph to another, keeping the style unchangedprivate static void copyAllRunsToAnotherParagraph(XWPFParagraph oldPar, XWPFParagraph newPar) { final int DEFAULT_FONT_SIZE = 10; for (XWPFRun run : oldPar.getRuns()) { String textInRun = run.getText(0); if (textInRun == null || textInRun.isEmpty()) { continue; } int fontSize = run.getFontSize(); System.out.println("run text = '" + textInRun + "' , fontSize = " + fontSize); XWPFRun newRun = newPar.createRun(); // Copy text newRun.setText(textInRun); // Apply the same style newRun.setFontSize( ( fontSize == -1) ? DEFAULT_FONT_SIZE : run.getFontSize() ); newRun.setFontFamily( run.getFontFamily() ); newRun.setBold( run.isBold() ); newRun.setItalic( run.isItalic() ); newRun.setStrike( run.isStrike() ); newRun.setColor( run.getColor() ); } }fontSize
仍然存在一些问题。有时POI无法确定运行的大小(我将其值写入控制台以跟踪它)并给出-1。当我自己设置字体时,它可以完美地定义字体的大小(例如,我在Word中选择一些段落并手动设置其字体,无论是大小还是字体系列)。但是当它处理另一个POI生成的文本时,有时会给出-1。因此,当POI设为-1时,我会引入
默认字体大小 (在上面的示例中为10)。
Calibri字体家族似乎出现了另一个问题。但是在我的测试中,POI默认情况下将其设置为Arial,所以我对默认fontFamily没有相同的技巧,因为它与fontSize相同。
其他字体属性(粗体,斜体等)效果很好。
可能所有这些字体问题都是由于在我的测试中,文本是从.doc文件复制而来的。如果输入的是.doc,请在Word中打开.doc文件,然后单击“另存为..”并选择.docx格式。然后在您的程序中仅使用
XWPFdocument而不是
HWPFdocument,我想这会没事的。



