如何从 excel sheet 中的单元格获取数值

How to get the Numneric Value from a cell in an excel sheet

Below is the my excel sheet snapshot and code. I am trying to get the values in numeric format for Dob column.

我试过用线

mapData.put(sheet.getRow(0).getCell(j).toString(), sheet.getRow(i+1).getCell(j).getNumericCellValue());

然而,这一行出现异常

java.lang.IllegalStateException: Cannot get a NUMERIC value from a STRING cell

下面是代码,第三列是Dob。我正在尝试在控制台中打印这些值。

package Practice;

import java.io.File;
import java.io.FileInputStream;
import java.util.Map;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataDrivenTest 
{
    @Test(dataProvider = "TestData")
    public void runTestData(Map<Object, Object> map )
    {
        System.out.println(map.get("Dob"));
    }

    @DataProvider(name = "TestData")
    public Object[][] getDataFromExcel() throws Exception
    {
        String path= "C:\Users\kumar.sushobhan\Documents\DataDrivenExcelData.xlsx";
        File file= new File(path);
        FileInputStream fis= new FileInputStream(file);     
        XSSFWorkbook wb= new XSSFWorkbook(fis);
        XSSFSheet sheet= wb.getSheetAt(0);
        wb.close();     
        int rowCount= sheet.getLastRowNum();
        int colCount= sheet.getRow(0).getLastCellNum();     
        //Define a object array
        Object[][] obj= new Object[rowCount][1];

        //Get the data from excel sheet
        for(int i=0; i<rowCount;i++)
        {
            Map<Object, Object> mapData= new HashedMap<Object, Object>();
            for(int j=0;j<colCount;j++)
            {               
                mapData.put(sheet.getRow(0).getCell(j).toString(), sheet.getRow(i+1).getCell(j).getNumericCellValue());
            }
            obj[i][0]= mapData;
        }
        return obj;
    }
}

这是来自文档

您可以在获取值之前检查单元格的类型

for(int i=0; i<rowCount;i++)
    {
        Map<Object, Object> mapData= new HashedMap<Object, Object>();
        for(int j=0;j<colCount;j++)
        {   
            if (sheet.getRow(i+1).getCell(j).getCellType() != CellType.STRING) {
                mapData.put(sheet.getRow(0).getCell(j).toString(), sheet.getRow(i+1).getCell(j).getNumericCellValue());
            } else {
                mapData.put(sheet.getRow(0).getCell(j).toString(), Double.parseDouble(sheet.getRow(i+1).getCell(j).getStringCellValue()));
            }
        }
        obj[i][0]= mapData;
    }