使用Java中的Apache POI读取上标excel文本

时间:2016-03-13 17:50:21

标签: java excel apache apache-poi superscript

我有一个Excel工作表,其中包含一些包含上标和超链接的文本单元格。超链接很容易提取,但我无法提取上标:/,程序检测到它像纯文本。 “8 ^ 2 - > 82”。 My Excel with superscript

代码

excel = WorkbookFactory.create(new File("filename.xlsx"));
        Sheet hoja = excel.getSheetAt(4);
        List<String> datos = new ArrayList<String>();

        List<String> links = new ArrayList<String>();

        //recorrido
        Iterator<Row> filas = hoja.rowIterator();
        while (filas.hasNext()) {
            Row fila = filas.next();
            Iterator<Cell> celdas = fila.cellIterator();
            while (celdas.hasNext()) {
                Cell celda = celdas.next();
                System.out.print(celda.toString() + " || ");
                datos.add(String.valueOf(celda));
                Hyperlink linkAddress = celda.getHyperlink();
                if (linkAddress != null) {
                    links.add(linkAddress.getAddress());
                }
            }
            System.out.println();
        }

代码显示了我如何包含单元格,只是代码探测。

我正在使用Apache POI 3.14。

1 个答案:

答案 0 :(得分:0)

我使用一些RichTextString属性解决了这个问题。我创建了两个方法来提取Cell的RichTextString的值和上标。 为了获得值,我们可能需要迭代并连接所有String内容,除了最后一个。最后一个总是完整的上标。

private static String getValue(XSSFRichTextString cellContent){
    String value = "";
    for (int i = 0; i < cellContent.numFormattingRuns() - 1; i++) {
        int lenVal = cellContent.getLengthOfFormattingRun(i);
        int iVal = cellContent.getIndexOfFormattingRun(i);
        value += cellContent.toString().substring(iVal, lenVal + iVal);
    }
    return value;
}
private static String getSuperScript(XSSFRichTextString cellContent) {
    int lenSuper = cellContent.getLengthOfFormattingRun(cellContent.numFormattingRuns() - 1);
    int iSuper = cellContent.getIndexOfFormattingRun(cellContent.numFormattingRuns() - 1);
    return cellContent.toString().substring(iSuper, lenSuper + iSuper);
}

从8 ^ 1获得 - >例如,value = 8,superScript = 1。 或者来自&#34;上标示例^ A,B&#34; - &GT; value =&#34;上标示例&#34;,superScript =&#34; A,B&#34;。