gpt4 book ai didi

java - 尝试在Java中使用xlsx读取并返回字符串数组

转载 作者:行者123 更新时间:2023-12-02 02:46:08 25 4
gpt4 key购买 nike

嗨,我一直在尝试使用 xssf 读取数组,但每次尝试返回字符串数组时,我总是搞砸。我知道我的代码很糟糕,而且我仍在学习如何使其工作,无论如何,这是我的代码,请友善地向我解释一下。谢谢!

public static String[][] xlsxReader(){
File fileIO = new File(FILE_NAME);
XSSFWorkbook wb;
String[][] data;
try {
wb = new XSSFWorkbook(fileIO);

//Get the first sheet
Sheet sheet = wb.getSheetAt(0);

//Iterate on each rows from the active sheet
Iterator<Row> rIterator = sheet.iterator();

//Cannot get the last column for some reason
data = new String[sheet.getLastRowNum()][sheet.getLastRowNum()*2];

//While the there is a next iteration of the row, continue loop
while(rIterator.hasNext()){
//Assign the entire row to the row class
Row row = rIterator.next();
int r = 0;
r++;

//Assign the entire row cell into cIterator, to count the number of columns
Iterator<Cell> cIterator = row.cellIterator();

//While there is a next iteration column, continue the loop
while(cIterator.hasNext()){
//Assign the column iterator to the cell
Cell cell = cIterator.next();
int c = 0;
c++;

//assign the data string.
data[r][c] = cell.getStringCellValue();
//System.out.print(cell.getRowIndex()+ "\t");
//System.out.print(data[r][c]+ "\t");
}
//System.out.print("\n");

}
wb.close();
return data;

} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}

}

最佳答案

我认为问题实际上出在你的索引行中... r 和 c 可能应该在循环外初始化

int r = 0;
int c = 0;

while(rows){
while(cols){
.../ do work
c++;
}
r++;
c = 0;
}

关于java - 尝试在Java中使用xlsx读取并返回字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44557918/

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