1.main方法(filePath 是 要读取的文件的路径)
public static void main(String[] args) throws IOException { String filePath = "C:\Users\admin\Desktop\1.xlsx"; List<PersonPhone> newList = readExcel(filePath); }
2.readExcel方法(获取每一个单元格数据后 可以按照自己实际处理方式来进行整理数据)
public static List<PersonPhone> readExcel(String filePath) throws IOException {//读取Excel并获取所有信息 File file = new File(filePath);//获取该路径文件 XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));//加载excel文本 Sheet sheet = workbook.getSheetAt(0);// 读取第一个 sheet List<PersonPhone> personPhone = new ArrayList<>(); Row row = null;//存储行数据对象 int rowCount = sheet.getPhysicalNumberOfRows();// 获得行总数 // 逐行处理 excel 数据 for (int i = 1; i < rowCount; i++) { row = sheet.getRow(i);//获得每一行的数据 if (row != null) { int coloumNum = sheet.getRow(0).getPhysicalNumberOfCells();// 获得咧总数 PersonPhone phone = new PersonPhone(); for (int j = 0; j < coloumNum; j++) { Cell cell = row.getCell(j);//获得一个单元格 if (cell != null) { if (j == 0) { //code phone.setCode(cell.toString()); } else if (j == 1) { phone.setName(cell.toString()); } else if (j == 2) { phone.setIsD(cell.toString()); } else { phone.setPhone(cell.toString()); } personPhone.add(phone); } } } workbook.close(); } return personPhone; }
3.完整代码
@Slf4j @Data public class PersonPhone { private String code; private String name; private String phone; private String isD; public static void main(String[] args) throws IOException { String filePath = "C:\Users\admin\Desktop\1.xlsx"; List<PersonPhone> newList = readExcel(filePath); } public static List<PersonPhone> readExcel(String filePath) throws IOException {//读取Excel并获取所有信息 File file = new File(filePath);//获取该路径文件 XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));//加载excel文本 Sheet sheet = workbook.getSheetAt(0);// 读取第一个 sheet List<PersonPhone> personPhone = new ArrayList<>(); Row row = null;//存储行数据对象 int rowCount = sheet.getPhysicalNumberOfRows();// 获得行总数 // 逐行处理 excel 数据 for (int i = 1; i < rowCount; i++) { row = sheet.getRow(i);//获得每一行的数据 if (row != null) { int coloumNum = sheet.getRow(0).getPhysicalNumberOfCells();// 获得咧总数 PersonPhone phone = new PersonPhone(); for (int j = 0; j < coloumNum; j++) { Cell cell = row.getCell(j);//获得一个单元格 if (cell != null) { if (j == 0) { //code phone.setCode(cell.toString()); } else if (j == 1) { phone.setName(cell.toString()); } else if (j == 2) { phone.setIsD(cell.toString()); } else { phone.setPhone(cell.toString()); } personPhone.add(phone); } } } workbook.close(); } return personPhone; } }