In reference to my previous question How to calculate number of rows in a column of Excel document using Java i was able to calculate the total number of columns in the given sheet. Now half of the work is yet to be done as i want to calculate the number of rows in a particular column. Possible solution could be using 2d array and storing column index and the total rows or using map, etc. How i can achieve this? Java code is provided here. I'm getting right count(column count) for my demo file. Please modify/suggest changes as required.
(edit): i've used hasp map to calculate store column index as key and row count as value, but it wasnt working, may be the applied logic was wrong. Well, if i want to accomplish this by using Hash Map, how i can store number of rows in a particular column(while iterating) as a value
Java Code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.poi.ss.formula.functions.Column;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelRead {
static int colrange=1000;
public static void main(String[] args) {
HashMap hm=new HashMap();
int count=0;
try {
FileInputStream file = new FileInputStream(new File("C:/Users/vinayakp/Desktop/Demo2.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
for(Row r:sheet)
{
short minColIx=r.getFirstCellNum();
short maxColIx=r.getLastCellNum();
for(short colIx=minColIx;colIx<maxColIx;colIx++) {
Cell c= r.getCell(colIx);
if(c!=null) {
if(c.getCellType()== Cell.CELL_TYPE_STRING||c.getCellType() == Cell.CELL_TYPE_NUMERIC||c.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
count++; ---// can i use hashcode in here to get the key and value pair? key=column index value=total number of rows in that column
}
}
else break;
}
}
System.out.println("\nTotal Number of columns are:\t"+count);
System.out.println(hm);
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException ae) {
ae.printStackTrace();
}
}
}