Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to get columns from Excel files using Apache POI?

In order to do some statistical analysis I need to extract values in a column of an Excel sheet. I have been using the Apache POI package to read from Excel files, and it works fine when one needs to iterate over rows. However I couldn't find anything about getting columns neither in the API (link text) nor through google searching.

As I need to get max and min values of different columns and generate random numbers using these values, so without picking up individual columns, the only other option is to iterate over rows and columns to get the values and compare one by one, which doesn't sound all that time-efficient.

Any ideas on how to tackle this problem?

Thanks,

like image 545
posdef Avatar asked May 27 '10 15:05

posdef


People also ask

Does Apache POI help to read Excel file?

To Read and Write Excel file in Java, Apache provides a very famous library POI. This library is capable enough to read and write both XLS and XLSX file format of Excel. To read XLS files, an HSSF implementation is provided by POI library.

How do I add a column in Excel using Apache POI?

Add a New Column In this method, we use a loop to go through all rows of the input Excel sheet. For each row, we first find its last cell number and then create a new cell after the last cell.


1 Answers

Excel files are row based rather than column based, so the only way to get all the values in a column is to look at each row in turn. There's no quicker way to get at the columns, because cells in a column aren't stored together.

Your code probably wants to be something like:

List<Double> values = new ArrayList<Double>();
for(Row r : sheet) {
   Cell c = r.getCell(columnNumber);
   if(c != null) {
      if(c.getCellType() == Cell.CELL_TYPE_NUMERIC) {
         valuesadd(c.getNumericCellValue());
      } else if(c.getCellType() == Cell.CELL_TYPE_FORMULA && c.getCachedFormulaResultType() == Cell.CELL_TYPE_NUMERIC) {
         valuesadd(c.getNumericCellValue());
      }
   }
}

That'll then give you all the numeric cell values in that column.

like image 97
Gagravarr Avatar answered Sep 20 '22 08:09

Gagravarr