[英]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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.