我有一个代码,它使用Apache从excel表中读取数据,并将其存储为字符串数组。但是我希望这个数据是一个双数组,因为我必须为了其他目的对它进行操作。
我尝试使用Double.parseDouble将字符串更改为双倍。但是从excel文件中读取的数据类似于@8bbab2f。
我还尝试将输出初始化为一个双数组,但是抛出了一个错误。
那么,如何使用Apache作为双数组获取数据呢?
我的代码如下:
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");
}
}
}
}发布于 2015-10-27 17:34:31
您应该使用getNumericCellValue()直接返回的双值,而不以非常奇怪的方式将其转换为字符串,并尝试将其转换回原来的值,即
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表中将所有值存储为数字值,那么只有单元格_TYPE_数值-case就足够了。
发布于 2015-10-27 16:35:31
这应该是可行的:
final DataFormatter dataFormatter = new DataFormatter();
String cellValueAsString dataFormatter.formatCellValue(cell);
double cellValueAsDouble = Double.parseDouble(cellValueAsString);我只测试过
cell instanceof XSSFCell不过。根据区域设置,您可能还需要这样做:
double cellValueAsDouble = Double.parseDouble(cellValueAsString.replace(',', '.'));不过,很有可能有更好的解决方案。
https://stackoverflow.com/questions/33372727
复制相似问题