Anthony Gawon Lee
Anthony Gawon Lee

Reputation: 375

Apache POI reading Excel data and putting them in a HashSet

I have a excel sheet called guitars.xlsx

| Guitar Name | Guitar Year | Guitar Maker |

| Les Paul | 1979 | Gibson |

| 800ce | 2013 | Taylor |

| Stratocaster | 1966 | Fender |

How would I use Apache POI to read this file and return these values in a HashSet?

Upvotes: 0

Views: 1393

Answers (2)

jlars62
jlars62

Reputation: 7383

You should search on your own for tutorials such as this one. Here is a pretty simple (untested) example though:

File excelFile = new File("guitars.xlsx");
Workbook excelWorkBook = new XSSFWorkbook(excelFile);
Set<String> data = new HashSet<String>();

for(Iterator<Row> rowIterator = excelWorkBook.getSheetAt(0).iterator(); rowIterator.hasNext();) {
    for(Iterator<Cell> cellIterator = rowIterator.next().cellIterator(); cellIterator.hasNext();) {
        data.add(cellIterator.next().getStringCellValue());
    }
}

Upvotes: 1

Alex Nevidomsky
Alex Nevidomsky

Reputation: 708

Something along these lines:

Workbook wb = WorkbookFactory.create(file);
Sheet worksheet = wb.getSheetAt(0);

String name;
for(int line=1; ; line++) {
    Row row = worksheet.getRow(line);
    Cell cell0 = row.getCell(0), cell1 = row.getCell(1), cell2 = row.getCell(2);
    String name, year, maker;

    if(cell0==null||(name=cell0.getStringCellValue())==null) break;
    year = cell1!=null? cell1.getStringCellValue():null;
    maker = cell2!=null? cell2.getStringCellValue():null;

    Record r = new Record(name, year, maker);
    set.add(r);
}

Don't forget to define hashCode() based on all the fields and equals() functions for Record to use it in HashSet.

Upvotes: 1

Related Questions