How to make a for loop with only strings and a fixed number of columns?
I have an Android app that reads from Excel. I want to replace a while loop and put in a for loop. I only have 3 columns, so I think this is another way to do it. Can you show me how to do this while the for loop only uses rows and 3 columns?
private void readExcelFile() {
try{
String inFileName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+"ola.xlsx";
File file = new File(inFileName);
Workbook workBook = WorkbookFactory.create(file);
Sheet sheet = workBook.getSheetAt(0);
Iterator<Row> rowIter = sheet.rowIterator();
//this is the loop I talked about
while(rowIter.hasNext()){
Row myRow =rowIter.next();
Iterator<Cell> cellIter = myRow.cellIterator();
while(cellIter.hasNext()){
Cell myCell = cellIter.next();
Toast.makeText(getApplicationContext(), "cell Value: " + myCell.toString(), Toast.LENGTH_SHORT).show();
}
}
}catch (Exception e){e.printStackTrace(); }
return;
}
source to share
// ... alternate looping logic using for loops
Sheet sheet = workBook.getSheetAt(0);
for (int row = 0; row < sheet.getColumns(); row++) {
for (int column = 0; column < sheet.getRows(); column++) {
Cell cell = sheet.getCell(column, row);
Toast.makeText(getApplicationContext(), "cellValue: " + cell.toString(), Toast.LENGTH_SHORT).show();
}
}
I looked into the JExcel library, it has getRows and getColumns methods that return no. rows and columns respectively. Hence, I could use iteration for loops instead of using iterators.
source to share
Well this is more of an algorithm than android, you can loop through cells if you have row and column size:
int totalCount = rowSize * columnSize;
Iterator<Cell> rowIter = sheet.rowIterator();
Iterator<Cell> cellIter;
for(int i = 0 ; i < totalCount ; i++){
if(i % rowSize == 0){
//Move to the Next Row
myRow = rowIter.next();
cellIter = myRow.cellIterator();
}
Cell myCell = cellIter.next();
}
Although it may have a bug or two, but I think it will work the way you want it to.
source to share
String FilePath = "E://airline.xls";
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);
Sheet sh = wb.getSheet("Sheet2");
for(int row = 0; row < sh.getRows(); row++){
for(int column = 0; column < sh.getColumns(); column++){
System.out.print(sh.getCell(column, row).getContents() + " ");
}
}
I did this using the JExcel library book class. Please see the documentation at [blog]: http://jexcelapi.sourceforge.net/resources/javadocs/2_6_10/docs/jxl/Workbook.html/ "JExcel Documentation".
It should be noted that getCell accepts row and column parameters. If we pass these parameters in another way, we get an Exception.
source to share