0

我正在尝试使用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());
        }
    }
}
4

1 回答 1

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>类型。有什么理由使用原始类型吗?

于 2011-01-31T12:03:54.173 回答