第1、引入包,這裏使用的的是maven,其餘工具本身百度。apache
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>4.1.1</version> </dependency>
第2、工具方法。maven
/** * 讀取指定 excel 文件 * * @param inputFilePath 絕對文件路徑 * @param rowBegin 開始讀取的行,注意從 1 開始 * @return */ public static Map<String, String> readDataFromExcel(String inputFilePath, int rowBegin) { Map<String, String> areas = new HashMap<>(); FileInputStream fileInput = null;//建立文件輸入流 XSSFWorkbook wb = null;//由輸入流文件獲得工做簿對象 try { fileInput = new FileInputStream(inputFilePath); wb = new XSSFWorkbook(fileInput); XSSFSheet sheet = wb.getSheetAt(0);//獲取第一個sheet int lastRowNum = sheet.getLastRowNum(); //獲取表格內容的最後一行的行數 //rowBegin表明要開始讀取的行號,下面這個循環的做用是讀取每一行內容 for (int i = rowBegin; i <= lastRowNum; ++i) { XSSFRow row = sheet.getRow(i);//獲取每一行 //由於個人文件是固定的,因此直接座標獲取了 String id = row.getCell(0).getStringCellValue().replace("CN", ""); String name = row.getCell(2).getStringCellValue(); String pro = row.getCell(7).getStringCellValue(); String city = row.getCell(9).getStringCellValue(); String key = pro + "省-" + city + "市-" + name; if (areas.containsKey(key)) { //重複的本身處理 //System.out.println(key); } areas.put(key, id); // 註釋掉的是常規循環過程 /*int columnNum = row.getLastCellNum();//獲取每一行的最後一列的列號,即總列數 for (int j=0; j<columnNum; ++j) { XSSFCell cell = row.getCell(j);//獲取每一個單元格 if (CellType.NUMERIC.equals(cell.getCellType())) { System.out.printf("%.0f\t", cell.getNumericCellValue()); } else { System.out.printf("%s\t", cell.getStringCellValue()); } } System.out.println();*/ } } catch (Exception e) { logger.error("讀取 地址 excel 文件錯誤!"); e.printStackTrace(); } finally { if (null != wb) { try { wb.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != fileInput) { try { fileInput.close(); } catch (IOException e) { e.printStackTrace(); } } } return areas; }