首页 > 解决方案 > 无法从数字单元格java中获取文本值

问题描述

当我尝试读取 excel 表时,我遇到了代码问题,如果它包含它将读取的文本,但它不读取它的数字并给我这个错误 Cannot get a text value from a numeric cell java

public static void main(String[] args) throws IOException, Exception {
    /*WebDriver dr;
    // TODO Auto-generated method stub
         dr = new FirefoxDriver();
        dr.get("https://www.example.com/");
        ArrayList<String> username=readExcelData(0);
        ArrayList<String> pass=readExcelData(1);
        for(int i=0; i<username.size();i++) {
        dr.findElement(By.id("email")).sendKeys(username.get(i));
        dr.findElement(By.id("pass")).sendKeys(pass.get(i));
        dr.findElement(By.id("loginbutton")).click();
        Thread.sleep(6000);
        dr.findElement(By.id("email")).clear();
        dr.findElement(By.id("pass")).clear();
        }*/

// it work with txt 
//readExcelData(0);
// it will not work with the number 
//readExcelData(1);

}

public static  ArrayList<String> readExcelData(int colNo) throws IOException {
    FileInputStream fis= new FileInputStream("C:\\dat.xls");
    HSSFWorkbook wb=new HSSFWorkbook(fis);
    HSSFSheet s=wb.getSheet("sh1");
    Iterator<Row> rowIterator=s.iterator();
    rowIterator.next();
    ArrayList<String> list=new ArrayList<String>();
    while (rowIterator.hasNext()) {

        list.add( rowIterator.next().getCell(colNo).getStringCellValue());
    }
    System.out.println("List :::"+list);
    return list;
}

标签: javaselenium

解决方案


试试下面的代码:

public static  ArrayList<String> readExcelData(int colNo) throws IOException {
            FileInputStream fis= new FileInputStream("C:\\dat.xls");
            HSSFWorkbook wb=new HSSFWorkbook(fis);
            HSSFSheet s=wb.getSheet("sh1");
            Iterator<Row> rowIterator=s.iterator();
            rowIterator.next();
            ArrayList<String> list=new ArrayList<String>();
            DataFormatter formatter = new DataFormatter();

            while (rowIterator.hasNext()) {
                 String val = formatter.formatCellValue(rowIterator.next().getCell(colNo));
                list.add(val);
            }
            System.out.println("List :::"+list);
            return list;
        }

推荐阅读