简体   繁体   English

无法从 NUMERIC 单元格中获取 STRING 值?

[英]Cannot get a STRING value from a NUMERIC cell?

I Was Executing Test Scripts Though Excel Sheet Using Keyword Driven Data Framework.我正在使用关键字驱动的数据框架通过 Excel 工作表执行测试脚本。

While Executing Am Geting Error as :执行时出现错误:

java.lang.RuntimeException: java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell java.lang.RuntimeException: java.lang.IllegalStateException: 无法从 NUMERIC 单元格中获取 STRING 值

My Selenium Code is我的硒代码是

    package DemoData;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import DataConfig.ExcelDataConfig;

public class ReadArrayData 
{

    WebDriver driver;


  @Test(dataProvider="Tipreports")
  public void Dataprovider(String username, String password) throws InterruptedException
  {
      System.setProperty("webdriver.chrome.driver", "F:\\New folder\\chromedriver.exe");

      driver = new ChromeDriver();

      driver.get("http://xxxxxxxxxxxxxxxx/");

      driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

      driver.manage().window().maximize();

      driver.findElement(By.id("txt_username")).sendKeys(username);

      driver.findElement(By.id("txt_pin")).sendKeys(password);

      driver.findElement(By.xpath("//*[@id='btn_click']")).click();

      Thread.sleep(5000);

      //driver.getCurrentUrl();

      Assert.assertTrue(driver.getCurrentUrl().contains("http://xxxxxxxxxxxxx/Algorithm_Run.aspx"),"User Not able to Login - Invalid Credentials");   

  }

  @AfterMethod
  public void Close()
  {
      driver.quit();
  }

  @DataProvider(name="Tipreports")
  public Object[][] passdata()
  {

      ExcelDataConfig config = new ExcelDataConfig("E:\\Workspace\\KeywordFramework\\TestData\\Dataprovider.xlsx");
         int rows = config.getRowCount(0);

         Object[][] data = new Object[rows][2];

         for(int i=0;i<rows;i++)
         {
             data[i][0]=config.getData(0, i, 0);
             data[i][1]=config.getData(0, i, 1);

         }
        return data;

  }

}

Here is My Excel Data Config Code :这是我的 Excel 数据配置代码:

package DataConfig;

import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelDataConfig 
{
    XSSFWorkbook wb;
    XSSFSheet Sheet1;

    public ExcelDataConfig(String excelpath)
    {
        try
        {
            File src = new File(excelpath);
            FileInputStream fis = new FileInputStream(src);
            wb= new XSSFWorkbook(fis);
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }

    public String getData(int sheetnumber, int row, int column)
    {
        Sheet1 = wb.getSheetAt(sheetnumber);

        String data =Sheet1.getRow(row).getCell(column).getStringCellValue();

        return data;

    }

    public int getRowCount(int sheetindex)
    {
        int row = wb.getSheetAt(sheetindex).getLastRowNum();

        row = row+1;

        return row;
    }

}

Can you please help me to sort out this, Why am getting this error?你能帮我解决这个问题,为什么会出现这个错误? I have declared 2 Columns and 4 Rows using for loop.我已经使用 for 循环声明了2 Columns and 4 Rows But am getting cannot Get The error as cannot get the string value from Numeic Cell.但是我正在获取无法获取错误,因为无法从 Numeic Cell 获取字符串值。

Try this:尝试这个:

String data;

if(cell.getCellType()==CellType.STRING) 
    data = cell.getStringCellValue(); 
else if(cell.getCellType()==CellType.NUMERIC) 
    data = String.valueOf(cell.getNumericCellValue());
else ...

It is a better way to retrieve the cell content as text.这是将单元格内容作为文本检索的更好方法。

Thanks to @AxelRichter, the manual show a more complete example to retrieve cell content: https://poi.apache.org/components/spreadsheet/quick-guide.html#CellContents感谢@AxelRichter,手册显示了一个更完整的示例来检索单元格内容: https ://poi.apache.org/components/spreadsheet/quick-guide.html#CellContents

//try this:
DataFormatter objDefaultFormat = new DataFormatter();
FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
String cellValueStr = objDefaultFormat.formatCellValue( cell , formulaEvaluator );

DataFormatter contains methods for formatting the value stored in an Cell. DataFormatter 包含格式化存储在单元格中的值的方法。 This can be useful when you need to get data exactly as it appears in Excel.当您需要完全按照 Excel 中显示的方式获取数据时,这会很有用。 Supported formats include currency, SSN, percentages, decimals, dates, phone numbers, zip codes, etc.支持的格式包括货币、SSN、百分比、小数、日期、电话号码、邮政编码等。

Thanks to @AxelRichter:感谢@AxelRichter:

DataFormatter formatter = new DataFormatter();
String text = formatter.formatCellValue(cell);

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

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