作为双数组POI读取数据

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

我试着改变string使用Double.parseDouble加倍。 但从Excel文件中读取的数据变成这样的@ 8bbab2f。

我也尝试初始化输出为双数组,但引发错误。

那么如何使用Apache POI将数据作为double数组来获取?

我的代码如下:

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值,而不是以非常奇怪的方式将其转换为String,并尝试将其转换回来,即

 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[]

顺便说一句,我也会检查为什么还有string格式的值,你正在尝试阅读。 如果将所有值都作为数值存储在Excel工作表中,则只有CELL_TYPE_NUMERIC-case应该足够了。

这应该工作:

 final DataFormatter dataFormatter = new DataFormatter(); String cellValueAsString dataFormatter.formatCellValue(cell); double cellValueAsDouble = Double.parseDouble(cellValueAsString); 

我只用了

 cell instanceof XSSFCell 

虽然。 根据区域设置,您可能也需要这样做:

 double cellValueAsDouble = Double.parseDouble(cellValueAsString.replace(',', '.')); 

尽pipe有最好的解决办法。