簡體   English   中英

如何將docx文件表單元格中的完整文本轉換為單個字符串

[英]how to get complete text which is in a docx file table cell into a single string

我正在嘗試使用docx4j api以Java代碼獲取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());
        }
    }
}

這部分看起來可疑:

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>也是通用類型。 有什么理由要使用原始類型嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM