【发布时间】:2015-04-23 07:30:38
【问题描述】:
我在 Excel 中有这样的公式:
=IF(A1="foo";"";"0")
如果公式返回一个空白值,我希望 POI 创建的结果 csv 文件中没有值。如果公式返回 0,我希望在我的 csv 文件中有一个 0。
这是我的代码的一部分(这始终是剥离代码多少的问题):
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
boolean isFirst = true;
for (int cn = 0; cn < row.getLastCellNum(); cn++) {
Cell cell = row.getCell(cn, Row.CREATE_NULL_AS_BLANK);
if (!isFirst) {
buffer.write(delimiter.getBytes(charset));
} else {
isFirst = false;
}
// Numeric Cell type (0)
// String Cell type (1)
// Formula Cell type (2)
// Blank Cell type (3)
// Boolean Cell type (4)
// Error Cell type (5)
if (cell.getCellType() == 0 || cell.getCellType() == 2) {
try {
if (DateUtil.isCellDateFormatted(cell)) {
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
Date value = cell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
if (cell.getNumericCellValue() < 1) {
sdf.applyPattern("HH:mm:ss");
}
buffer.write(sdf.format(value).getBytes(charset));
} else {
double valueDouble = cell.getNumericCellValue();
if (valueDouble == Math.ceil(valueDouble)) {
buffer.write(String.format("%d", (long) valueDouble).getBytes(charset));
} else {
valueDouble = round(valueDouble, roundingPlaces);
String value = String.valueOf(valueDouble).replace(".", ",");
buffer.write(value.getBytes(charset));
}
}
} catch (Exception e) {
// Formula returns a string
cell.setCellType(Cell.CELL_TYPE_STRING);
String value = cell.getStringCellValue();
buffer.write(value.getBytes(charset));
}
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
String value = cell.getStringCellValue();
buffer.write(value.getBytes(charset));
}
}
buffer.write("\r\n".getBytes(charset));
}
此代码在每种情况下都会在 csv 文件中生成 0。它是由这条线产生的
double valueDouble = cell.getNumericCellValue();
documentation 很清楚这一点:
double getNumericCellValue()以数字形式获取单元格的值。
对于字符串,我们抛出异常。对于空白单元格,我们返回 0。对于 我们返回预先计算的值的公式或错误单元格;
如果单元格包含 NULL 值,我如何分析它?
【问题讨论】:
-
能不能不用
cell.setCellType(Cell.CELL_TYPE_BLANK); -
我一开始不知道怎么调查细胞……
标签: java excel apache-poi