2011-01-31 64 views
0

我正在試圖使用docx4j api獲取java代碼中的docx文件表格數據。 在這裏,我試圖獲取每個單元格的數據在一次。如何獲得該數據..我在我的代碼有遞歸方法調用。如何將docx文件表格單元格中的完整文本轉換爲單個字符串

static void walkList1(List children) { 
    i=children.size(); 
    int i=1; 
    for (Object o : children) { 
     if (o instanceof javax.xml.bind.JAXBElement) { 
      if (((JAXBElement) o).getDeclaredType().getName() 
        .equals("org.docx4j.wml.Text")) { 
       org.docx4j.wml.Text t = (org.docx4j.wml.Text) ((JAXBElement) o) 
       .getValue(); 
       System.out.println(" 1 1 " + t.getValue()); 
      } 
     } 
     else if (o instanceof org.docx4j.wml.R) { 
      org.docx4j.wml.R run = (org.docx4j.wml.R) o; 
      walkList1(run.getRunContent()); 
     } else { 
      System.out.println(" IGNORED " + o.getClass().getName()); 
     } 
    } 
} 

回答

0

這部分看起來很可疑:

i=children.size(); 
int i=1; 

首先必須是一個可變的靜態字段(否則你的代碼將無法編譯),這通常是一個壞主意。第二個是本地的方法,但從未使用過。

如果你想所有的內容組合成一個單一的String我建議你創建一個StringBuilder並傳遞到你的遞歸調用,例如:

static String walkList(List children) { 
    StringBuilder dst = new StringBuilder(); 
    walkList1(children, dst); 
    return dst.toString(); 
} 
static void walkList1(List children, StringBuilder dst) { 
    for (Object o : children) { 
     if (o instanceof javax.xml.bind.JAXBElement) { 
      if (((JAXBElement) o).getDeclaredType().getName() 
        .equals("org.docx4j.wml.Text")) { 
       org.docx4j.wml.Text t = (org.docx4j.wml.Text) ((JAXBElement) o) 
       .getValue(); 
       dst.append(t); 
      } 
     } 
     else if (o instanceof org.docx4j.wml.R) { 
      org.docx4j.wml.R run = (org.docx4j.wml.R) o; 
      walkList1(run.getRunContent(), dst); 
     } else { 
      System.out.println(" IGNORED " + o.getClass().getName()); 
     } 
    } 
} 

而且List<T>JAXBElement<T>是通用的類型。是否有任何理由使用原始類型?

相關問題