简体   繁体   English

使用Apache POI读取ms excel时未保留前导零

[英]Leading zeros not retained while reading ms excel with apache POI

I am trying to read .xlsx file in java (using Apache POI API) whose cell contain values having leading zeros. 我试图读取Java(使用Apache POI API)中的.xlsx文件,其单元格包含具有前导零的值。 eg 0590040100000124 例如0590040100000124

But in output i get something like this 但是在输出中我得到这样的东西

6247241.0 <-> 5.90040100000124E14 <-> 0.0 <-> 5.90020100000125E14 <-> Here is my code 6247241.0 <-> 5.90040100000124E14 <-> 0.0 <-> 5.90020100000125E14 <->这是我的代码

public static void main(String[] args) throws FileNotFoundException, IOException  {
    // TODO Auto-generated method stub
    try{
    Workbook workbook = new XSSFWorkbook(new FileInputStream("C://dedup//dedup.xlsx"));
    String sheetName= workbook.getSheetName(0);
    System.out.println("Sheet Name:"+sheetName);
    double cellValues[] = new double[1000];

     for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);


            int cellIndex=0;

            for (Row row : sheet) {
                for (Cell cell : row) {
                        //if(cell.toString()!=null){
                         cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cellValues[cellIndex]=cell.getNumericCellValue();
                        cellIndex++;
                        //}
                    }
            }
            for(int k=0;k<cellValues.length;k++)
                System.out.print(cellValues[k]+" <-> "+"\t");
        }
    }catch(Exception e){
        System.out.println("JKB Exception Message:"+e.getMessage());
    }

Your problem is that you're fetching the value as a double (Numbers in Excel are,except for a few edge cases, stored as floating point numbers). 您的问题是您要获取一个双精度值(Excel中的数字(除少数情况外,均存储为浮点数))。 Floating point numbers printed from Java have no leading zeros, use scientific format etc 从Java打印的浮点数没有前导零,使用科学格式等

Assuming what you really wanted was "give me a string that looks like what Excel shows for this cell", then you don't want to be printing the raw double value. 假设您真正想要的是“给我一个看起来像Excel为该单元格显示的字符串”,那么您就不想打印原始double值。 Instead, you need to use the DataFormatter class , which provides methods which read the Excel format rules applied to a cell, then re-creates (as best it can) those in Java 相反,您需要使用DataFormatter类该类提供的方法可读取应用于单元格的Excel格式规则,然后(尽可能)重新创建Java中的规则。

Your code should be: 您的代码应为:

DataFormatter fmt = new DataFormatter();

String numberAsInExcel = fmt.formatCellValue(cell);

That will format the number based on the formatting rules applied in Excel, so should return it looking as you expect, with leading zero, non-scientific format etc 这将根据Excel中应用的格式设置规则对数字进行格式化,因此应按预期方式返回数字,并带有前导零,非科学格式等

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

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