2013-09-30 78 views

回答

1

以下示例顯示了從docx文件讀取上標/下標的方法。 Doc也會類似。

package demo.poi; 

import org.apache.poi.openxml4j.exceptions.InvalidFormatException; 
import org.apache.poi.openxml4j.opc.OPCPackage; 
import org.apache.poi.xwpf.usermodel.VerticalAlign; 
import org.apache.poi.xwpf.usermodel.XWPFDocument; 
import org.apache.poi.xwpf.usermodel.XWPFParagraph; 
import org.apache.poi.xwpf.usermodel.XWPFRun; 
import org.junit.Test; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.util.Iterator; 

public class DocReaderTest { 

    @Test 

    public void showReadDocWithSubscriptAndSuperScript() throws IOException, InvalidFormatException { 
     File docFile = new File("C:/temp/sample.docx"); 

     XWPFDocument hdoc = new XWPFDocument(OPCPackage.openOrCreate(docFile)); 

     Iterator<XWPFParagraph> paragraphsIterator = hdoc.getParagraphsIterator(); 
     while (paragraphsIterator.hasNext()) { 
      XWPFParagraph next = paragraphsIterator.next(); 
      for (XWPFRun xwrun : next.getRuns()) { 
       VerticalAlign subscript = xwrun.getSubscript(); 
       String smalltext = xwrun.getText(0); 
       switch (subscript) { 
        case BASELINE: 
         System.out.println("smalltext, plain = " + smalltext); 
         break; 
        case SUBSCRIPT: 
         System.out.println("smalltext, subscript = " + smalltext); 
         break; 
        case SUPERSCRIPT: 
         System.out.println("smalltext, superscript = " + smalltext); 
         break; 
       } 
      } 
     } 
    } 
} 
+0

雖然我執行你的代碼,它顯示'方法getRuns未定義的類型XWPFParagraph'錯誤。我把'junit-4.1.jar'和'poi-ooxml-3.5-FINAL.JAR'文件,我不知道如何糾正這個錯誤?請幫我解決這個錯誤。 –

相關問題