Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get number of columns of a particular row in given excel using Java

I want the number of columns of a particular row in excel. How is that possible? I used POI API

but I could get only columns count to 7 .

    try             {                 fileInputStream = new FileInputStream(file);                 workbook = new HSSFWorkbook(fileInputStream);                 Sheet sheet = workbook.getSheet("0");                   int numberOfCells = 0;                 Iterator rowIterator = sheet.rowIterator();                 /**                  * Escape the header row *                  */                 if (rowIterator.hasNext())                 {                     Row headerRow = (Row) rowIterator.next();                     //get the number of cells in the header row                     numberOfCells = headerRow.getPhysicalNumberOfCells();                 }                 System.out.println("number of cells "+numberOfCells);  } 

I want the number of columns at a particular row number say 10 . The excel columns are not same

like image 927
muthukumar Avatar asked Aug 28 '13 13:08

muthukumar


People also ask

How do I count rows in Excel in Java?

getLastRowNum() return index of last row. So if you wants to know total number of row = getLastRowNum() +1.

How do I find out how many columns a column has in Excel?

Just click the column header. The status bar, in the lower-right corner of your Excel window, will tell you the row count. Do the same thing to count columns, but this time click the row selector at the left end of the row. If you select an entire row or column, Excel counts just the cells that contain data.

What is XSSFWorkbook in Java?

XSSFWorkbook − This class has methods to read and write Microsoft Excel and OpenOffice xml files in . xls or . xlsx format. It is compatible with MS-Office versions 2007 or later.


1 Answers

There are two Things you can do

use

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells(); 

or

int noOfColumns = sh.getRow(0).getLastCellNum(); 

There is a fine difference between them

  1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
  2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'
like image 75
Abhishek Singh Avatar answered Sep 21 '22 13:09

Abhishek Singh