简体   繁体   English

使用Apache POI如何检索数字单元格值作为整数

[英]Using Apache POI how retrieve a numeric cell value as an integer

I have created a program which creates excel sheet, which is having some data column 1 - contains String column 2- contains number (which is basically an integer, but while reading why it is getting converted to Float ?) 我创建了一个创建Excel工作表的程序,该程序具有一些数据列1-包含字符串列2-包含数字(基本上是整数,但是在阅读为什么将其转换为Float吗?)

    public class ApachePOI8 {

        public static void main(String[] args) {

            String file = "C:\\Eclipse workspace\\PoiExample\\Excel8.xlsx";

            Workbook wb = new XSSFWorkbook();       
            Sheet sheet = wb.createSheet("Sheet1");
            sheet.protectSheet("Pwd1"); //This statements locks the entire sheet with password: Pwd1

            DataFormat fmt = wb.createDataFormat();   //created a textStyle, which prevents Excel to interprate data, in short it means it will be taken as String
            CellStyle textStyle = wb.createCellStyle();
            textStyle.setDataFormat(fmt.getFormat("@"));
            textStyle.setLocked(false);

            CellStyle numerStyle = wb.createCellStyle();
            numerStyle.setDataFormat(fmt.getFormat("0"));
            numerStyle.setLocked(false);


                    Row row0 = CellUtil.getRow(0, sheet);
                    for (int columnIndex = 0; columnIndex<4; columnIndex++){
                        Cell cell = CellUtil.getCell(row0, columnIndex);
                            if(columnIndex == 0) {
                                cell.setCellStyle(textStyle);
                                cell.setCellValue("Product 1");
                            }else if(columnIndex == 1) {                            
                                cell.setCellStyle(numerStyle);
                                cell.setCellValue(1);

                            }
                        }   
                            else{
                                cell.setCellStyle(textStyle);

                            }    
                     } //end of for Loop


            try {
                FileOutputStream outputStream = null;
                outputStream = new FileOutputStream(file);
                wb.write(outputStream);
                outputStream.close();
                System.out.println("Done!");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

}

Now to read the excel sheet which got generated 现在阅读生成的excel表格

public class ApachePOIExcelRead {

    private static final String FILE_NAME = "C:\\Eclipse workspace\\PoiExample\\Excel8.xlsx";
    public static void main(String[] args) {

        try {
            FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
            Workbook workbook = new XSSFWorkbook(excelFile);
            Sheet datatypeSheet = workbook.getSheetAt(0);
            Iterator<Row> iterator = datatypeSheet.iterator();

            while (iterator.hasNext()) {

                Row currentRow = iterator.next();
                Iterator<Cell> cellIterator = currentRow.iterator();

                while (cellIterator.hasNext()) {

                    Cell currentCell = cellIterator.next();
                    //getCellTypeEnum shown as deprecated for version 3.15
                    //getCellTypeEnum ill be renamed to getCellType starting from version 4.0
                    if (currentCell.getCellTypeEnum() == CellType.STRING) {
                        System.out.print("String: "+currentCell.getStringCellValue() + "\n");
                    } else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
                        System.out.print("NUMERIC "+currentCell.getNumericCellValue() + "\n");
                    }

                }
                System.out.println();

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

But I am getting the output as String: Product 1 NUMERIC 1.0 String: 12-12-12 但是我得到的输出为String:产品1 NUMERIC 1.0 String:12-12-12

Why is it so that the number which is entered ie 1 is coming in float NUMERIC 1.0 ? 为什么要输入的数字(即1 )出现在浮点型NUMERIC 1.0中

Kindly suggest. 请提示。

getNumericCellValue() returns a double . getNumericCellValue()返回double

As far as POI is concerned all numeric values are floating point. 就POI而言,所有数值均为浮点数。 You can just convert the returned double to int or long if you need it to be an integer, truncating in the process. 您只需将返回的double转换为intlong如果您需要将其作为整数,则可以在过程中截断。

System.out.print("NUMERIC " + ((int)currentCell.getNumericCellValue()) + "\n");

But be aware that you may occasionally get surprising results for the numeric values of formula cells, whose operands are non-integers, that "should" produce an integer result. 但是请注意,对于操作数不是整数的公式单元格的数值,您偶尔会得到令人惊讶的结果,即“应该”产生整数结果。 The actual result may not be exactly an integer, and you might end up truncating and be off by 1. For all the gory details read What Every Computer Scientist Should Know About Floating-Point Arithmetic 实际结果可能不完全是整数,您可能最终会被截断并偏离1。有关所有杂点的详细信息,请阅读每位计算机科学家应了解的有关浮点算法的知识。

Answering my own question, as I have got the solution and I hope this might be helpful to others :) 回答我自己的问题,因为我已经找到了解决方案,我希望这可能对其他人有所帮助:)

DataFormat format = sheet1.getWorkbook().createDataFormat();
            CellStyle costprice = bulkUploadSpreadSheet.getWorkbook().createCellStyle();
            costprice.setDataFormat(format.getFormat("#"));

Now you can apply the costprice cell style to the desired cell. 现在,您可以将costprice单元格样式应用于所需的单元格。 Please do let me know if you any other solution for this. 如果您有其他解决方案,请告诉我。 All the best. 祝一切顺利。

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

相关问题 如何使用Apache POI在具有公式的单元格上设置数值? - How to set Numeric value on cell that has a formula using Apache POI? 在java中使用Apache POI从数字单元格中读取整数 - Read integer from numeric cell using Apache POI in java 如何检查Apache POI中数字单元格的空白? - How to check for emptiness of a numeric cell in Apache POI? 如何正确地将这个“奇怪的”单元格值转换为 Date 对象,使用 Apache POI 检索解析 Excel? - How to correctly convert into a Date object this "strange" cell value retrieve parsing an Excel using Apache POI? 如何使用apache poi从公式单元格中读取单元格值 - How to read cell value from formula cell using apache poi 如何检查excel整数中的单元格或不在apache POI中 - How to check a cell in excel integer or not in apache POI 在Apache Poi 3.7中使用特定格式在数字单元格中写入Double值 - Write Double value in numeric cell with specific format in Apache Poi 3.7 Apache POI setCellType无法正确设置数值的单元格类型 - Apache POI setCellType not correctly setting cell type for numeric value 如何使用Apache POI在Excel中添加公式(单元格的动态值) - How Add a formula(Dynamic value of cell) in Excel Using Apache POI 如何使用 apache poi 3.1 获取公式单元格值(数据) - How to get the formula cell value(data) using apache poi 3.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM