###第一步:下载java POI jar包并导入到java工程
###第二步:获取excel中第一行第一列的内容(.xls .xlsx均可)
//由于此处仅作示例,所以没有捕获异常
Workbook wb = WorkbookFactory.create(new FileInputStream("MyExcel.xlsx"));
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
String string = cell.getStringCellValue();
System.out.println(string);
##-------------------15秒教程到此结束-------------------
###通过上面的快速教程,相信大家一定都对java POI有了一点感性的认识。
##下面来点干货,读取excel文件中一个sheet的所有内容:
/*
* 读取.xls文件,导入hssf包
* 读取.xlsx文件,导入xssf包
* 读取以上两种格式的文件,导入ss包
* Excel(ss = hssf + xssf) - 来自java POI官网
*
*/
Workbook wb = WorkbookFactory.create(new FileInputStream("MyExcel.xlsx"));
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
System.out.print(cellRef.formatAsString());
System.out.print(" - ");
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue());
} else {
System.out.println(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
System.out.println(cell.getCellFormula());
break;
default:
System.out.println();
}
}
}