Groovy ApachePOI:为什么在不';如果单元格为空,则不会发生?
我正在创建一个Groovy脚本,以便将表从.xlsm文件导出到.csv文件,并在适当时包含公式(而不是生成的数据)。当脚本在当前单元格上调用.getCellType()时,我会得到一个空指针异常,即使此功能发生在测试单元格是否为空的if语句中 我试着换了新的Groovy ApachePOI:为什么在不';如果单元格为空,则不会发生?,groovy,apache-poi,xssf,Groovy,Apache Poi,Xssf,我正在创建一个Groovy脚本,以便将表从.xlsm文件导出到.csv文件,并在适当时包含公式(而不是生成的数据)。当脚本在当前单元格上调用.getCellType()时,我会得到一个空指针异常,即使此功能发生在测试单元格是否为空的if语句中 我试着换了新的 if(cell != null) 条件 if(cell.getCellType() != CellType.BLANK) 无济于事 下面是代码和完整的错误消息 #!/usr/bin/env groovy @Grab(
if(cell != null)
条件
if(cell.getCellType() != CellType.BLANK)
无济于事
下面是代码和完整的错误消息
#!/usr/bin/env groovy
@Grab(group = 'org.apache.poi', module = 'poi', version = '4.1.0')
@Grab(group = 'org.apache.poi', module = 'poi-ooxml', version = '4.1.0')
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.usermodel.*
Workbook wb = new XSSFWorkbook("input.xlsm")
FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator()
DataFormatter formatter = new DataFormatter()
PrintStream out = new PrintStream(new FileOutputStream("output.csv"), true, "UTF-8")
byte[] bom = [(byte)0xEF, (byte)0xBB, (byte)0xBF]
out.write(bom)
for (Sheet sheet : wb){
for (Row row : sheet) {
boolean firstCell = true
for(Cell cell : row){
if (! firstCell) out.print(',')
if ( cell != null ) {
if (fe != null) cell = fe.evaluateInCell()
String value = formatter.formatCellValue(cell)
if (cell.getCellType() == CellType.FORMULA) {
value = "=" + value
}
out.print(value)
}
firstCell = false
}
out.println()
}
}
错误消息:
Caught: java.lang.NullPointerException: Cannot invoke method
getCellType() on null object java.lang.NullPointerException:
Cannot invoke method getCellType() on null object
at ExcelToCSV.run(ExcelToCSV.groovy:28)
我的期望是,在当前单元格不为null的情况下,如果计算该单元格以包含公式,则输出到.csv文件的字符串的开头将附加一个“=”,否则它将只输出表示单元格内值的字符串
不幸的是,我的IDE跳过断点时遇到了问题,目前我无法单步执行代码或查看变量值,这是我正在处理的另一个问题。在我解决这个问题之前,我希望有人能够指出我可能遗漏了什么。在空检查之后,但在调用
cell
方法之前,您将分配给cell
。该赋值必须为空值
evaluateInCell
接受类型为Cell
的参数,因此如果替换行
if (fe != null) cell = fe.evaluateInCell()
// cell == null
与
然后得到javadocs所说的应该得到的结果,对于简单值,它是不变的单元格,对于公式,它是公式结果
我想您还会发现,单元格类型将发生变化,以反映公式计算返回的值的类型,因此您对
CellType.formula
的测试将始终为false。在调用任何方法之前,您需要检查单元格是否为null,例如getCellType
Yes,这就是我在方法调用所在的if语句中所做的,还是我遗漏了什么?正如我所说的,在无法设置断点的情况下进行调试是一个挑战。为什么要使用?大多数时候,这不是人们想要的。如果(fe!=null)cell=fe.evaluateInCell()则删除行,然后改为执行String value=formatter.formatCellValue(cell,fe)
。并且,如果希望公式字符串的前导为=
,则if(cell.getCellType()==CellType.formula)value=“=”+cell.getCellFormula()
if (fe != null) cell = fe.evaluateInCell(cell)