Apache POI读取Excel数据并将它们放入HashSet中

时间:2015-04-17 23:06:34

标签: java apache-poi

我有一张名为guitars.xlsx

的excel表
| Guitar Name | Guitar Year | Guitar Maker |

| Les Paul | 1979 | Gibson |

| 800ce | 2013 | Taylor |

| Stratocaster | 1966 | Fender |

如何使用Apache POI读取此文件并在HashSet中返回这些值?

2 个答案:

答案 0 :(得分:1)

这些方面的东西:

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);
}

不要忘记基于Record的所有字段和equals()函数定义hashCode()以在HashSet中使用它。

答案 1 :(得分:1)

您应该自己搜索this one等教程。这是一个非常简单(未经测试)的例子:

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());
    }
}