简体   繁体   English

Java从Excel读取数据

[英]Java read data from Excel

I want to read data from Excel - only numbers so I can compare it later, I go in a loop and I have code like this: 我想从Excel中读取数据-仅是数字,以便以后进行比较,我陷入了循环,并且我有如下代码:

int type = cell.getCellType();
    switch(type){
    case 0:
        int value = (int)cell.getNumericCellValue();
    case 1:
        String temp = cell.getStringCellValue();
        int value = Integer.parseInt(temp);

    }

It's like this because sometimes data in Excel have numeric type, sometimes string type. 之所以这样,是因为Excel中的数据有时具有数字类型,有时具有字符串类型。

Now my questions. 现在我的问题。 Is casting to int a good idea? int转换为int是个好主意吗? If I have number 1.200 in a cell with type String so it's "1.200" how to convert it to int (or float if it's better)? 如果我在类型为String的单元格中有数字1.200 ,那么它是“ 1.200”如何将其转换为int (如果更好的话,可以float )? What is the best way to do it? 最好的方法是什么?

All I need is - numbers (sometimes from String cell types) so I can compare it with numbers from another datasource. 我需要的只是-数字(有时是String单元格类型),因此我可以将其与另一个数据源中的数字进行比较。

CellType.Numeric refers to cells whose contents contain integers , fractions or dates . CellType.Numeric是指其内容包含整数分数日期的单元格

Therefore, if you are reading cells that can potentially have more than one specific numeric type then you will need to put in further work to narrow the classification. 因此,如果您正在读取可能具有多个特定数字类型的单元格,则需要进行进一步的工作以缩小分类范围。

getNumericCellValue() returns a double (assuming the cell is of type CellType.Numeric ) getNumericCellValue()返回一个double (假设单元格的类型为CellType.Numeric

Casting this double to int will result in the decimal and all digits after being dropped. 将此doubleint将导致删除后的小数和所有数字。 So 1.200 would become 1 . 因此1.200将变为1 Hence it is likely in your case that casting it as a float is better. 因此,在您的情况下,将其转换为float会更好。 If you want to ensure no loss in accuracy then don't cast at all; 如果您想确保准确性不受影响,那么就不要投射。 just save it as a double . 只需将其保存为double

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM