gpt4 book ai didi

java - 将数据读取为双数组 POI

转载 作者:行者123 更新时间:2023-12-01 22:03:05 26 4
gpt4 key购买 nike

我有一个代码,它使用 Apache POI 从 Excel 工作表读取数据并将其存储为字符串数组。但我希望这个数据是一个 double 数组,因为我必须为了其他目的而操纵它。

我尝试使用 Double.parseDouble 将字符串更改为 double 。但是从excel文件中读取的数据变成了这样的@8bbab2f。

我还尝试将输出初始化为 double 组,但抛出错误。

那么如何使用 Apache POI 获取双数组形式的数据?

我的代码如下:

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;



public class XLRead {

public static void main(String args[]) throws Exception {
Scanner in = new Scanner(System.in);
String wb_name;
wb_name = in.next();

File excel = new File("/Users/Documents/Sample_data/" + wb_name);
FileInputStream fis = new FileInputStream(excel);


HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sh = wb.getSheet("sample");

int rowNum = sh.getLastRowNum() + 1;
//System.out.println(rowNum);
int colNum = sh.getRow(0).getLastCellNum();
//System.out.println(colNum);

String[][] X0 = new String[rowNum][colNum];
// Here i tried to define X0 as double[][]. But it doesn't work.
for (int i = 3; i < 368; i++){
HSSFRow row = sh.getRow(i);
//System.out.println(row);
for (int j = 4; j <= 27; j++){
HSSFCell cell = row.getCell(j);
//System.out.println(cell);
String value = cellToString(cell);
X0[i][j] = value;
//System.out.println(value);
}
}
}
public static String cellToString(HSSFCell cell){
// i tried changing this function to public static double cellToDouble(HSSFCell cell)
int type;
Object result = null;
type = cell.getCellType();
if(cell!=null){
if (type == Cell.CELL_TYPE_FORMULA)
{
switch (cell.getCachedFormulaResultType()){
case Cell.CELL_TYPE_NUMERIC:
result = cell.getNumericCellValue();

break;
case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
default:
throw new RuntimeException("Data type not applicable");
}
}
}
}

最佳答案

您应该使用 getNumericCellValue() 直接返回的 double 值,而不是以一种非常奇怪的方式将其转换为字符串并尝试将其转换回来,即

public static double getCellValue(HSSFCell cell){

switch (cell.getCachedFormulaResultType()){
case Cell.CELL_TYPE_NUMERIC:
return cell.getNumericCellValue();

break;
case Cell.CELL_TYPE_STRING:
return Double.parse(cell.getStringCellValue());
break;
default:
throw new RuntimeException("Data type not applicable");
}
}

然后将结果值放入double[]中。

顺便说一句,我还会检查为什么仍有您试图读取的字符串格式的值。如果您将所有值都以数值形式存储在 Excel 工作表中,则仅使用 CELL_TYPE_NUMERIC 大小写就足够了。

关于java - 将数据读取为双数组 POI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33372727/

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