java - 将单元格值导出为字符串的安全方法
问题描述
String
使用Apache POI获取单元格值的安全方法是什么?
对于一些非空单元格,我得到以下异常:
com.monitorjbl.xlsx.exceptions.NotSupportedException: null
at com.monitorjbl.xlsx.impl.StreamingCell.getSheet(StreamingCell.java:330)
at org.apache.poi.ss.usermodel.DataFormatter.isDate1904(DataFormatter.java:313)
at org.apache.poi.ss.usermodel.DataFormatter.getFormat(DataFormatter.java:309)
at org.apache.poi.ss.usermodel.DataFormatter.getFormattedNumberString(DataFormatter.java:868)
at org.apache.poi.ss.usermodel.DataFormatter.formatCellValue(DataFormatter.java:1021)
at org.apache.poi.ss.usermodel.DataFormatter.formatCellValue(DataFormatter.java:971)
at org.apache.poi.ss.usermodel.DataFormatter.formatCellValue(DataFormatter.java:950)
...
我现在使用下面的代码将单元格值提取为文本:
import org.apache.poi.ss.usermodel.*;
private static DataFormatter formatter = new DataFormatter();
private static String formatCellValue(Cell cell) {
return formatter.formatCellValue(cell);
}
该方法的javadoc说:
无论单元格类型如何,都将单元格的格式化值作为字符串返回。如果无法解析 Excel 格式模式,则单元格值将使用默认格式进行格式化。当传递一个空或空白单元格时,此方法将返回一个空字符串 ("")。不会计算公式类型单元格中的公式。
解决方案
解决方案是将检查添加到提到的方法并调用,与在 POI 单元格getStringCellValue()
上StreamingCell
调用它相比,它总是安全的。
private static String formatCellValue(Cell cell) {
if (cell instanceof com.monitorjbl.xlsx.impl.StreamingCell) {
return cell.getStringCellValue();
}
return formatter.formatCellValue(cell);
}
推荐阅读
- javascript - 在窗口中滚动添加哈希到 url + 添加类
- canoe - CANoe工具DBC配置
- javascript - nodejs GET端点的问题
- database - SQLSTATE [23000]:违反完整性约束:19 NOT NULL 即使在使必填字段为空之后
- c - 我们如何使用 C 语言在 .DAT 文件中编写多个结构?
- sql - 在 Postgres 中使用 COALESCE 并按结果值分组
- mysql - django 错误 1146 “表 'buysell.sell_sellform' 不存在”
- javascript - 如何将索引连接到 Reactjs 元素中的函数
- java - 如何在junit 5扩展中获得重复计数
- nuxt.js - 在 Nuxt 中使用 eslint 和 prettier?