1
def Reader = new CSVReader(new FileReader("/Users/me/myfile.csv"));
while ((row = Reader.readNext()) != null) {   

How can I do the above with the same format for an xlsx file. I've looked into some options like POI, but i'm not sure how to do exactly what I have above. The examples I saw seemed to require additional code for retrieving the value from a row. In my current case, with opencsv, i just get a row which is a String[] which I can then use like this value = row[index]

tim_yates
  • 167,322
  • 27
  • 342
  • 338
LemonMan
  • 2,963
  • 8
  • 24
  • 34

1 Answers1

3

Xslx is a binary format so you can't read it as it were plain text and splitting on something.

You will have to use POI or another library to read excel's files. If you use POI the best way to implement your code is as follow:

FileInputStream file = new FileInputStream(new File("/Users/me/myfile.xsls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt("name of sheet");
for( Row row : sheet.iterator()) {
//reading new row
Cell cell = row.getCell(<your index here>)
//then you can read cell with cell.getStringCellValue()
}

Hope it helps

ejoncas
  • 329
  • 2
  • 13
  • thanks! this is helpful as a starting point, but is there a way to first convert each row, perhaps using the iterator into string[], so that i dont have to rewrite the large amount of code which accesses values like this row[index]? – LemonMan Jun 11 '13 at 21:19
  • Sure, just read all possible 256 columns, and put that into a `new String[ 256 ]` array – tim_yates Jun 11 '13 at 21:25
  • why 256? is that the excel max or something? well i think i have 112, anyway String[i]=row.getCell(i)? the problem with this is i'll be putting in a cell object not a string/int so I guess I could go String[i]=row.getCell(i).toString()? – LemonMan Jun 11 '13 at 21:37
  • Yes, 256 is the max allowed number of columns in an excel file. Of course you can do that but is far away for being performance. I suggest you to update your code, you only have to change row[] for row.getCell(). Find and replace will do the magic! – ejoncas Jun 11 '13 at 23:45