Seleniuim с Java: выборка данных из файла Excel не получает полный вывод на консоли - PullRequest
0 голосов
/ 01 июня 2018

Я пытаюсь с помощью следующего кода получить все данные Excel.Количество строк в Excel - 5, а столбцов - 20.

PFB ниже кода

package testRunner;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;

public class ReadWriteExcel {

    public static void main(String args[])
    //public static void ReadExcel() throws IOException
    {
        try
        {
        //Specify the File path which you want to Create or Write
    File src=new File("D:\\eclipse-workspace\\CucumberWithTestNGForSelenium\\PersonalInformation.xlsx");
    //Load the file
    FileInputStream fis=new FileInputStream(src);
    //Load the Workbook
    @SuppressWarnings("resource")
    XSSFWorkbook wb=new XSSFWorkbook(fis);
    //get the sheet which you want to modify or create
    XSSFSheet sh1=wb.getSheetAt(0);

    //Finding the number of rows
    int firstRow=sh1.getFirstRowNum();
    int lastRow=sh1.getLastRowNum()+1;
    int no_of_rows=lastRow-firstRow;



    for(int i=0;i<no_of_rows;i++)
    {
        //Finding the number of Columns

        int no_of_columns=sh1.getRow(i).getLastCellNum();


        for(int j=0;j<no_of_columns;j++)
        {
    System.out.print(" "+ sh1.getRow(i).getCell(j).getStringCellValue()+ " ");
        }
        System.out.println();
    }
        }
        catch(Exception e)
        {
            e.getMessage();
        }}}

И в консоли первая строка отображает все столбцы, но из второй строки - ее отображениетолько 3-4 столбца.

PFB

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.poi.openxml4j.util.ZipSecureFile$1 (file:/C:/Users/Mehak/.m2/repository/org/apache/poi/poi-ooxml/3.17/poi-ooxml-3.17.jar) to field java.io.FilterInputStream.in
WARNING: Please consider reporting this to the maintainers of org.apache.poi.openxml4j.util.ZipSecureFile$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
 Title  FirstName  LastName  EmailValidation  Password  Date  Month  Year  SignUpCheckbox  AddessFirstName  AddressLastName  Company  MainAddress  AddressLine2  city  State  PostalCode  Country  Mobile  AddressAlias 
 Mr  Simon Duffy  aduffy@abc.com

enter image description here

Продолжение Excel на втором изображении: _

enter image description here

Ответы [ 2 ]

0 голосов
/ 06 июня 2018

Можете ли вы попробовать изменить System.out.print(" "+ sh1.getRow(i).getCell(j).getStringCellValue()+ " "); внутри цикла for с помощью приведенного ниже кода и проверить, решает ли он вашу проблему.

DataFormatter formatter = new DataFormatter();
String val = formatter.formatCellValue(sh1.getRow(i).getCell(j));
System.out.print(" "+ val + " ");

ИЛИ

String val = sh1.getRow(i).getCell(j).toString();
System.out.print(" "+ val + " ");

ИЛИ

System.out.print(" "+ sh1.getRow(i).getCell(j)+ " ");
0 голосов
/ 05 июня 2018

Я предлагаю вам взглянуть на Cell getStringCellValue() документы java:

/**
 * Get the value of the cell as a string
 * <p>
 * For numeric cells we throw an exception. For blank cells we return an empty string.
 * For formulaCells that are not string Formulas, we throw an exception.
 * </p>
 * @return the value of the cell as a string
 */
String getStringCellValue();

Возможно, CellType других ячеек в строке 2 не относится к типу STRING.Вы можете попробовать написать вспомогательный метод следующим образом (работает с poi 3.16):

private static String myCellStringValue(Cell cell, CellType cellType) {
 String data = EMPTY;

 try {
  switch (cellType) {
   case STRING:
    data = cell.getRichStringCellValue().toString();
    break;
   case NUMERIC:
    data = String.valueOf(cell.getNumericCellValue());
    break;
   case BOOLEAN:
    data = String.valueOf(cell.getBooleanCellValue());
    break;
   case FORMULA:
    data = myCellStringValue(cell, cell.getCachedFormulaResultTypeEnum());
    break;
   case BLANK:
   case ERROR:
   case _NONE:
    break;
  }
 } catch (Exception e) {
  //your catch clause
 }
 return data;
}

И затем вызвать вспомогательный метод в вашем цикле:

for (int j = 0; j < no_of_columns; j++) {
 Cell cell = sh1.getRow(i).getCell(j);
 System.out.print(" " + myCellStringValue(cell, cell.getCellTypeEnum()) + " ");
}
...