gpt4 book ai didi

java - 解决错误的请求无法从 void 转换为 HSSFCell

转载 作者:行者123 更新时间:2023-12-03 02:52:53 28 4
gpt4 key购买 nike

我正在尝试从包含公式的 Excel 文件中读取数据,并将数据写入另一个 Excel 的特定列,但通过使用下面的代码,我收到一条错误消息,例如:Cannot Convert from void to HSSFCell at第 68 行。

 @Test 

public void SampleCustNumFormat() throws Exception {

String [] myXL = getExcelData();

//Write Data into Excel.


//See what has been read from Excel
System.out.println (" Before Loop " + myXL[1]);

for (int i=0; i<xRows; i++){
System.out.println (" Cust Num " + myXL[i]);
}

FileOutputStream out = new FileOutputStream ("C:\\SCE docs\\Automation\\TestExcelData.xls");
HSSFWorkbook myWB = new HSSFWorkbook();
HSSFSheet sheet = myWB.getSheetAt(0);

for (int k=1; k<=sheet.getLastRowNum(); k++)
{
HSSFCell cell = sheet.getRow(1).createCell(2).setCellValue(myXL[k]);
}
myWB.write(out);
out.close();
}




public String [] getExcelData() throws Exception{

String [] tabArray=null;

FileInputStream fi = new FileInputStream("C:\\SCE docs\\Automation\\CustomerAccount_Information.xls");
HSSFWorkbook myWB = new HSSFWorkbook(fi);
HSSFSheet mySheet = myWB.getSheetAt(0);

FormulaEvaluator evaluator = myWB.getCreationHelper().createFormulaEvaluator();

xRows = mySheet.getLastRowNum()+1;
tabArray = new String [xRows];

for (int i=0;i<xRows;i++)
{
HSSFRow row = mySheet.getRow(i);
HSSFCell cell = row.getCell(3);
CellValue cellValue = evaluator.evaluate(cell);
String value = evaluateFormula(cellValue);
tabArray[i]=value;
}
return tabArray;

}





private String evaluateFormula(CellValue cellValue) throws Exception{

int type = cellValue.getCellType();

Object result=null;

switch (type) {

case HSSFCell.CELL_TYPE_BOOLEAN:
result = cellValue.getBooleanValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
result = cellValue.getNumberValue();
break;
case HSSFCell.CELL_TYPE_STRING:
result = cellValue.getStringValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
break;


// CELL_TYPE_FORMULA will never happen
case HSSFCell.CELL_TYPE_FORMULA:
break;
}

return result.toString();
}
}

最佳答案

这些行引起了麻烦:

for (int k=1; k<=sheet.getLastRowNum(); k++)
{
HSSFCell cell = sheet.getRow(1).createCell(2).setCellValue(myXL[k]);
}

在这里,您将从工作表中获取第一行,在索引 2 处创建一个单元格,然后设置单元格值...并将所有这些分配给 Cell!但是,setCellValue 返回一个void(如 API 中所示)。所以基本上,您需要将这些行分成两部分,如下所示:

for (int k=1; k<=sheet.getLastRowNum(); k++)
{
HSSFCell cell = sheet.getRow(1).createCell(2);
cell.setCellValue(myXL[k]);
}

按照这种方式,您将首先创建单元格并将其分配给单元格。然后,您可以设置该值。

编辑:或者,您可以(正如 Sankumarsingh 指出的那样)不分配该值并在一行中完成所有操作,如下所示:

for (int k=1; k<=sheet.getLastRowNum(); k++)
{
sheet.getRow(1).createCell(2).setCellValue(myXL[k]);
}

关于java - 解决错误的请求无法从 void 转换为 HSSFCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18259828/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com