我有一个 Excel 工作表,其中包含一些包含上标和超链接的文本单元格。超链接很容易提取,但我无法提取上标:/,程序将其检测为纯文本。 “8^2 --> 82”。
代码
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。
最佳答案
我使用一些 RichTextString 属性解决了这个问题。我创建了两种方法来提取单元格的 RichTextString 的值和上标。 为了获取该值,我们可能需要迭代并连接除最后一个之外的所有字符串内容。最后一个始终是完整的上标。
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 获得。 或者来自“上标示例 ^ A,B”--> value="superscript example", superScript="A,B"。
关于java - 在 Java 中使用 Apache POI 读取上标 excel 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35973636/