所需jar包:
下载地址:
maven配置:
UTF-8
org.apache.poi
poi-ooxml
3.10-FINAL
xls和xlsx文件:office excel2007以后版本为xlsx,以前的版本为xls
读取xlsx文件:
InputStream is = new FileInputStream(file);
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
// 获取每一个工作薄
for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
if (xssfSheet == null) {
continue;
}
String sheetName = xssfSheet.getSheetName();
System.out.println("标签名:"+sheetName);
// 获取当前工作薄的每一行
for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if (xssfRow != null) {
XSSFCell one = xssfRow.getCell(0);
//读取第一列数据
XSSFCell two = xssfRow.getCell(1);
//读取第二列数据
XSSFCell three = xssfRow.getCell(2);
//读取第三列数据
}
}
}
//转换数据格式
private String getValue(XSSFCell xssfRow) {
if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
return String.valueOf(xssfRow.getBooleanCellValue());
} else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
return String.valueOf(xssfRow.getNumericCellValue());
} else {
return String.valueOf(xssfRow.getStringCellValue());
}
}
读取xls文件:
InputStream is = new FileInputStream(file);
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
// 获取每一个工作薄
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 获取当前工作薄的每一行
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow != null) {
HSSFCell one = hssfRow.getCell(0);
//读取第一列数据
HSSFCell two = hssfRow.getCell(1);
//读取第二列数据
HSSFCell three = hssfRow.getCell(2);
//读取第三列数据
}
}
}
// 转换数据格式
private String getValue(HSSFCell hssfCell) {
if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
return String.valueOf(hssfCell.getBooleanCellValue());
} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
return String.valueOf(hssfCell.getNumericCellValue());
} else {
return String.valueOf(hssfCell.getStringCellValue());
}
}
注意上述代码需要excel中有列名·