【问题标题】:how to get complete text which is in a docx file table cell into a single string如何将docx文件表格单元格中的完整文本转换为单个字符串
【发布时间】:2011-01-31 06:15:29
【问题描述】:

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

【问题讨论】:

    标签: java docx docx4j


    【解决方案1】:

    这部分看起来很可疑:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多