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; } }