poi解析excle文件(xls,xlsx)

时间:2023-03-08 16:06:39

解析xls文件

/**
* 解析xls文件
*
* @param path 文件路径
* @throws Exception
*/
public static void showXls(String path) throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(new File(path)));
HSSFSheet sheet = null;
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {// 获取每个Sheet表
sheet = workbook.getSheetAt(i);
for (int j = 0; j < sheet.getLastRowNum() + 1; j++) {// getLastRowNum,获取最后一行的行标
HSSFRow row = sheet.getRow(j);
if (row != null) {
for (int k = 0; k < row.getLastCellNum(); k++) {// getLastCellNum,是获取最后一个不为空的列是第几个
if (row.getCell(k) != null) { // getCell 获取单元格数据
System.out.print(row.getCell(k) + "\t");
} else {
System.out.print("\t");
}
}
}
System.out.println(""); // 读完一行后换行
}
System.out.println("读取sheet表:" + workbook.getSheetName(i) + " 完成");
}
}

  解析xlsx文件

/**
* 解析xlsx文件
*
* @param path 文件路径
* @throws Exception
*/
public static void showXlsx(String path) throws Exception {
File excelFile = new File(path);
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(excelFile));
XSSFSheet sheet = wb.getSheetAt(0);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {// 获取每个Sheet表
sheet = wb.getSheetAt(i);
for (int j = 0; j < sheet.getLastRowNum() + 1; j++) {// getLastRowNum,获取最后一行的行标
XSSFRow row = sheet.getRow(j);
if (row != null) {
for (int k = 0; k < row.getLastCellNum(); k++) {// getLastCellNum,是获取最后一个不为空的列是第几个
if (row.getCell(k) != null) { // getCell 获取单元格数据
System.out.print(row.getCell(k) + "\t");
} else {
System.out.print("\t");
}
}
}
System.out.println(""); // 读完一行后换行
}
System.out.println("读取sheet表:" + wb.getSheetName(i) + " 完成");
}
}

  解析xls和xlsx文件

/**
* 解析xls和xlsx文件
*
* @param path 文件路径
* @throws Exception
*/
public static void showExcel(String path) throws Exception {
String fileType = path.substring(path.lastIndexOf(".") + 1, path.length());
Workbook wb = null;
if ("xls".equals(fileType)) {
wb = new HSSFWorkbook(new FileInputStream(new File(path)));
} else {
wb = new XSSFWorkbook(new FileInputStream(path));
}
Sheet sheet = null;
for (int i = 0; i < wb.getNumberOfSheets(); i++) {// 获取每个Sheet表
sheet = wb.getSheetAt(i);
for (int j = 0; j < sheet.getLastRowNum() + 1; j++) {// getLastRowNum,获取最后一行的行标
Row row = sheet.getRow(j);
if (row != null) {
for (int k = 0; k < row.getLastCellNum(); k++) {// getLastCellNum,是获取最后一个不为空的列是第几个
if (row.getCell(k) != null) { // getCell 获取单元格数据
System.out.print(row.getCell(k) + "\t");
} else {
System.out.print("\t");
}
}
}
System.out.println(""); // 读完一行后换行
}
System.out.println("读取sheet表:" + wb.getSheetName(i) + " 完成");
}
}

  

main方法

 public static void main(String[] args) throws Exception {
showExcel("E:\\upload\\测试.xls");
}