1

I'm working on a little app with Java on Netbeans, and I need to export the data of Excel file to an array and then work on this array. To get the excel I use Apache POI and I can show the value of the excel file in the consol.

However, I need to put it in an array, and for the moment I don't know how to work with the Iterator because I am getting the excel data into an iterator.

Workbook workbook = WorkbookFactory.create(new File(pathConfig1));
//File
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
Sheet sheet = workbook.getSheetAt(nbSheet1);
//Get index sheet user

Iterator<Row> rowIterator = sheet.rowIterator();
int nbLine= sheet.getLastRowNum() +1; 
//Number of Lines

int nbCol = sheet.getRow(0).getLastCellNum(); 
// Number of columns

String [][]data= new String[nbLine][nbCol];
//Array for the data

From this point I don't really know how to export the data in my array... Any idea ?

I thought to use 2 loop for but I don't know how to increment my Iterator...

2 Answers 2

1

As what I've understood, you want to store the every cell values in each row in an array right? If that's the case yes, you're right to use 2 loops and the iterator is optional in this case. I've rewritten your code and hope it helps.

Workbook workbook = WorkbookFactory.create(new File(pathConfig1));
// Iterator<Sheet> sheetIterator = workbook.sheetIterator();
Sheet sheet = workbook.getSheetAt(0);
// Iterator<Row> rowIterator = sheet.rowIterator(); 
int nbLine = sheet.getLastRowNum() + 1;
int nbCol = sheet.getRow(0).getLastCellNum();
String[][] data = new String[nbLine][nbCol];
for (int i = 0; i < nbLine; i++) {
    Row row = sheet.getRow(i);
    for (int j = 0; j < nbCol; j++) {
        Cell cell = row.getCell(j);
        data[i][j] = cell.toString();
    }
}
// Display
for (int i = 0; i < nbLine; i++) {
    StringBuffer buff = new StringBuffer();
    int j = 0;
    for (; j < nbCol - 1; j++) {
        buff.append(data[i][j]);
        buff.append(",");
    }
    buff.append(data[i][j]);
    System.out.println(buff.toString());
}
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not familiar with the specific library you're using, but an easy way to use iterators is in a for each loop

Something like

for (Sheet sheet : workbook.sheetIterator()) {
    for (Row row : sheet.rowIterator()) {
        data[row][col] = //row.getCellValue()? Like I said, I don't know this library
    }
}

1 Comment

I was thinking about something like that too at the beginning, first time I use this library! Thanks for try btw ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.