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啮齿动物评论中所述,如果得到java.lang.NoClassDefFoundError: org/openxmlformats/schemas/*something*,则必须使用https://poi.apache.org/faq.html#faq-N10025中提到的完整ooxml-schemas-1.3.jar。

对我而言,此代码无需使用此代码即可运行,因为我不使用Phonetic Guide Propertieshttps://msdn.microsoft.com/en-us/library/office/documentformat.openxml.wordprocessing.rubyproperties.aspx)。我使用Office 2007。

08-04 15:03