有什么方法可以识别 Apache POI xwpf 文档的字符样式吗?

Is there any way to identify character styles with Apache POI xwpf documents?

Here 我们看到 "HWPF" (MS Word 2000 .doc) 文件的 Apache POI 有一个方法 CharacterRun.getStyleIndex()... 通过它你可以,看起来,确定适用于此 运行...

字符 样式(不是段落样式)

但是对于 XWPF 东西(MS Word 2003+ .docx)文件,我找不到任何方法来识别 XWPFRun 对象中的字符样式。

以下代码应该从 XWPFDocument 中的所有运行 [1] 中获取所有样式,并打印它们的 XML 如果它们被应用为字符样式:

import java.io.FileInputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STStyleType;

import java.util.List;

public class WordGetRunStyles {

 public static void main(String[] args) throws Exception {

  FileInputStream fis = new FileInputStream("This is a Test.docx");
  XWPFDocument xdoc = new XWPFDocument(fis);

  List<XWPFParagraph> paragraphs = xdoc.getParagraphs();
  for (XWPFParagraph paragraph : paragraphs) {
   List<XWPFRun> runs = paragraph.getRuns();
   for (XWPFRun run : runs) {
    CTRPr cTRPr = run.getCTR().getRPr();
    if (cTRPr != null) {
     if (cTRPr.getRStyle() != null) {
      String styleID = cTRPr.getRStyle().getVal();
      System.out.println("Style ID=====================================================");
      System.out.println(styleID);
      System.out.println("=============================================================");
      XWPFStyle xStyle = xdoc.getStyles().getStyle(styleID);
      if (xStyle.getType() == STStyleType.CHARACTER) {
       System.out.println(xStyle.getCTStyle());
      }
     }
    }
   }
  }
 }
}

[1]请不要尝试使用内容过多的文档;-)。

正如@mike rodent 的评论中提到的,如果你得到 java.lang.NoClassDefFoundError: org/openxmlformats/schemas/*something* 那么你必须使用 https://poi.apache.org/faq.html#faq-N10025 中提到的完整 ooxml-schemas-1.3.jar。 =16=]

对我来说,这段代码运行时没有这个,因为我不使用 Phonetic Guide Properties (https://msdn.microsoft.com/en-us/library/office/documentformat.openxml.wordprocessing.rubyproperties.aspx)。我使用 Office 2007。