gpt4 book ai didi

java - 从不同列使用 Excel、ArrayList 和 Java 打印简单值 如果具有值的 Number 行之间不存在匹配,则不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:05 24 4
gpt4 key购买 nike

我想做的只是使用以下代码使用 for 循环和 arraylist 从多个列打印多个值

// =========The SpreadSheet=========

File src = new File("J:\\Excel files\\mutiselect.xlsx");

// Load file
FileInputStream fis = new FileInputStream(src);

// Load WB
XSSFWorkbook wb = new XSSFWorkbook(fis);

// Load Sheet
XSSFSheet sh1 = wb.getSheetAt(0);


List<String> values = new ArrayList<String>(); //values from excel will be stored within this array

Iterator<Row> rows = sh1.rowIterator();


while (rows.hasNext())
{

Row row = rows.next();

if (row.getRowNum() > 0)
{

values.add(row.getCell(1).getStringCellValue());

}
}

System.out.println(values);


Thread.sleep(2000);


List<String> values2 = new ArrayList<String>(); //values from excel will be stored within this array

Iterator<Row> rows2 = sh1.rowIterator();


while (rows2.hasNext())
{

Row row2 = rows2.next();

if (row2.getRowNum() > 0)
{

values2.add(row2.getCell(2).getStringCellValue());

}
}

System.out.println(values2);

fis.close();
driver.quit();

如果 Excel 中 B 列和 C 列的记录数量匹配,则一切正常。

但是问题出现了,当具有值的行数之间不匹配时,它不会从其中一列或两列打印,这意味着如果 B 列上的值多于 C 列,或者 C 列上的值多于 B 列,则不会打印。

请引用此图片进行说明:

/image/4gb5T.png

如果 Excel 是这样的,则其中一列的值不会被打印,或者两列的值都不会打印

并给我这样的错误

Exception in thread "main" java.lang.NullPointerException
at one.MultiSelectWithForLoop.main(MultiSelectWithForLoop.java:57)

第 57 行引用此代码

values.add(row.getCell(1).getStringCellValue());

或者给我这个错误

Exception in thread "main" java.lang.NullPointerException
at one.MultiSelectWithForLoop.main(MultiSelectWithForLoop.java:99)

第 99 行引用此代码

values2.add(row2.getCell(2).getStringCellValue());

我想要做的是单独打印出每一列中的所有值,即使值的数量不匹配或者一列中的值比另一列少或多为此,我应该在代码中更改哪里?

P.S 该代码用于 Java 的 Selenium Webdriver

最佳答案

来自 getCell() documentation

If you ask for a cell that is not defined....you get a null.

当每列中的值数量不同时,Iterator 仍然有下一行,因此 rows.hasNext() 为 true,但单元格为空,因此 row.getCell(1)null

当您尝试从 null 单元格获取 getStringCellValue() 时,您会收到 NullPointerException

改变

if (row.getRowNum() > 0)

if (row.getRowNum() > 0 && row.getCell(1) != null) 

关于java - 从不同列使用 Excel、ArrayList 和 Java 打印简单值 如果具有值的 Number 行之间不存在匹配,则不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35917864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com