通过pio完成xls和xlsx 文件解析
代码如下
在这里插入代码片
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
String excelPath = "/Users/*****/Desktop/2.xlsx";
try {
String businessLine = "LIGHT_TRUCK";
File excel = new File(excelPath);
if (excel.isFile() && excel.exists()) {
String[] split = excel.getName().split("\\.");
Workbook wb;
FileInputStream fis = new FileInputStream(excel);
if ( "xls".equals(split[1])){
wb = new HSSFWorkbook(fis);
}else if ("xlsx".equals(split[1])){
wb = new XSSFWorkbook(fis);
}else {
System.out.println("文件类型错误!");
return;
}
Sheet sheet = wb.getSheet("轻卡关键零部件清单");
int firstRowIndex = sheet.getFirstRowNum()+2;
int lastRowIndex = sheet.getLastRowNum();
System.out.println("firstRowIndex: "+firstRowIndex);
System.out.println("lastRowIndex: "+lastRowIndex);
for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {
System.out.println("rIndex: " + rIndex);
Row row = sheet.getRow(rIndex);
if (row != null) {
int firstCellIndex = row.getFirstCellNum()+1;
int lastCellIndex = row.getLastCellNum();
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {
Cell cell = row.getCell(cIndex);
if (cell != null) {
System.out.println(cell.toString());
}
}
}
}
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
e.printStackTrace();
}