如何从Excel工作表中的单元格获取数值

问题描述 投票:0回答:1
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

enter image description here

下面是代码,在第三列中有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;
    }
}
java testng-dataprovider
1个回答
0
投票
您可以在获取值之前检查单元格的类型

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; }

© www.soinside.com 2019 - 2024. All rights reserved.