Reputation: 499
I am reading data into a 2D array from an excel file using Apache POI. I think my error lies in my array code, not the POI elements. I can't use any of my array data after the method is run, it's all null.
public class ExcelRead {
public static void main(String[] args) throws Exception {
File excel = new File ("C:/Users/user/Desktop/Files/Dashboards.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
int rowNum = sheet.getLastRowNum()+1;
int colNum = sheet.getRow(0).getLastCellNum();
String[][] data = new String[rowNum][colNum];
for (int i=0; i<rowNum; i++){
//get the row
XSSFRow row = sheet.getRow(i);
for (int j=0; j<colNum; j++){
//this gets the cell and sets it as blank if it's empty.
XSSFCell cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK);
String value = String.valueOf(cell);
System.out.println("Value: " + value);
}
}
System.out.println("End Value: " + data[2][2]);
}
}
Here's my output (the result is the same for any cell of the array, I'm just using [2][2] because I know it should have a value.
Value: Project Name
Value: Dashboard URL
Value: To Email
Value: From Email
Value: Jira Login
Value: Password (same for )
Value: Image Location
Value: Run Automation
Value: Project1
Value: ProjectURL
Value: [email protected]
Value: [email protected]
Value: QAAutomation
Value: QARocks#2
Value: test
Value: yes
Value: Project2
Value: https://projectURL
Value: [email protected]
Value: [email protected]
Value: QAAutomation
Value: QARocks#2
Value: test
Value: yes
End Value: null
So it is reading the data just fine. But doesn't store the data, because when I try to call a cell for later use, it is null. Is my first output (Value:"") printing the result of every time through the array iteration? I'm not sure if that makes sense, but it seems like it is reading the Excel file, spitting out the cells one by one, but not storing them for me to use later.
Upvotes: 0
Views: 2622
Reputation: 2953
Because data array doesn't contain anything. While reading from excel file you forgot to add that data in the array. And default value of String if not initialized is null
.
Consider adding data[i][j] = value;
after System.out.println("Value: " + value);
.
You will get the desired output.
Upvotes: 0
Reputation: 17846
you're just looping through the items and not saving them in the array.
to save it in the array you need to do something like:
array[i][j] = value;
in your case:
for (int i=0; i<rowNum; i++){
//get the row
XSSFRow row = sheet.getRow(i);
for (int j=0; j<colNum; j++){
//this gets the cell and sets it as blank if it's empty.
XSSFCell cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK);
String value = String.valueOf(cell);
System.out.println("Value: " + value);
data[i][j] = value;
}
}
Upvotes: 3