我的 Apache POI XSSF 存在问题,因为它无法读取空白单元格值。
我有一个实现 DefaultHandler 的类。在该类中,所有非空白单元格都可以从 startElement 和 endElement 方法读取。
我想读取数据单元格中间的空白单元格。
任何人都可以提供如何执行此操作的示例或有关如何调试此问题的说明吗?
最佳答案
今天遇到了同样的问题。我正在使用 XSSF 事件模型。但 XSSF 不会为空白列提供列元素或值元素。很可能是因为支持 XML 就是这样。
关键是检查单元格引用的属性(你知道Excel使用的A1、A2、A3)。属性被传递到 startElement()
回调方法。然后我们可以检测丢失的单元格引用。因此,如果我们获得前一列元素的 L1 并获得当前列元素的 N1,我们就知道 M1 是空白/缺失单元格。
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (qName.equals("c")) {
String newColRef = atts.getValue("r");
coverColumnDistanceWithNulls(currentColRef, newColRef);
并且 coverColumnDistanceWithNulls()
只是为 currentColRef 和 newColRef 之间每个缺失的单元格引用添加空值
private void coverColumnDistanceWithNulls(String fromColRefString, String toColRefString) {
int colRefDistance = getDistance(fromColRefString, toColRefString);
while (colRefDistance > 1) {
logger.debug("Covering distance with null");
rowValues.add(null);
--colRefDistance;
}
}
private int getDistance(String fromColRefString, String toColRefString) {
String fromColRef = getExcelCellRef(fromColRefString);
String toColRef = getExcelCellRef(toColRefString);
logger.debug("fromCol: {} toCol: {}", new Object[] {fromColRefString, toColRefString});
return excelCellReferenceOrder.get(toColRef) - excelCellReferenceOrder.get(fromColRef);
}
private String getExcelCellRef(String fromColRef) {
if (fromColRef != null) {
int i = 0;
for (;i < fromColRef.length(); i++) {
if (Character.isDigit(fromColRef.charAt(i))) {
break;
}
}
if (i == 0) {
return fromColRef;
}
else {
return fromColRef.substring(0, i);
}
}
return null;
}
关于java - 如何在 apache POI XSSF 中获取空白单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10480030/