Name,Branch,Collage ==> Headers in excel sheet
Sasi, CSE, JNTU-A
Sandeep, CIVIL, JNTU-H
我想设置这样的值并执行一些循环,直到相应标题的最后一列。
("Name", "Sasi")
("Name", "Sandeep")
Name,Branch,Collage ==> Headers in excel sheet
Sasi, CSE, JNTU-A
Sandeep, CIVIL, JNTU-H
我想设置这样的值并执行一些循环,直到相应标题的最后一列。
("Name", "Sasi")
("Name", "Sandeep")
试试 Apache POI。这是一个例子:
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("some_sheet.xlsx"));
HashMap<Integer, String> headers = new HashMap<Integer, String>();
HashMap<Object, String> cells = new HashMap<Object, String>();
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
if (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
int colNum = 0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
headers.put(colNum++, cell.getStringCellValue());
}
}
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
int colNum = 0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cells.put(getCharValue(cell), headers.get(colNum++));
}
}
file.close();
headers.entrySet().forEach(entry->{
System.out.println(entry.getKey() + " " + entry.getValue());
});
cells.entrySet().forEach(entry->{
System.out.println(entry.getKey() + " " + entry.getValue());
});
} catch (Exception e) {
e.printStackTrace();
}
}
private static Object getCharValue(Cell cell) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
return cell.getNumericCellValue();
case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();
}
return null;
}
您需要以下依赖项:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
根据 apache poi 文档getStringCellValue()
,如果单元格类型为数字,则会引发异常。
作为解决方案,您可以使用cell.getCellType()
和调用相关getXXXCellValue()
方法检查类型。