JAVA读取xls文件和xlsx文件

时间:2022-02-26 13:58:29

所需jar包:

下载地址:
http://download.csdn.net/detail/zhengyikuangge/9533831


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;
}
// 获取当前工作薄的每一行
for (int rowNum = 0; 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);
//读取第三列数据
//需要转换数据的话直接调用getValue获取字符串
}
}
}
//转换数据格式
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 = 0; 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);
//读取第三列数据
//需要转换数据的话直接调用getValue获取字符串
}
}
}
// 转换数据格式
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中有列名·