@Data public class ExeclDto { /** * execl表 */ private String filename; /** * 需要匹配的工作表名 */ private String name1; /** * 需要匹配的工作表名 */ private String name ...
@Data public class ExeclDto { /** * execl表 */ private String filename; /** * 需要匹配的工作表名 */ private String name1; /** * 需要匹配的工作表名 */ private String name2; }
@SpringBootTest @Slf4j class CmmcysApplicationTests { @Test public void testReadExcel() throws IOException, InvalidFormatException { // 讀取的excel文件路徑 String filename = "src/main/resources/static/xlsx/車型名稱映射.xlsx"; String filename_new = "src/main/resources/static/xlsx/結果表.xlsx"; // 判斷filename是否為空 if (!StringUtils.isEmpty(filename)) { //讀取excel ExeclDto execlDto = new ExeclDto(); execlDto.setFilename(filename); execlDto.setName1("A"); execlDto.setName2("B"); Map<String, String> map = readExcel(execlDto); //如果map非空就寫入 if (!map.isEmpty()) { List list = new ArrayList<>(); for (Map.Entry<String, String> entry : map.entrySet()) { CarDto carDto = new CarDto(); carDto.setName_a(entry.getKey()); carDto.setName_b(entry.getValue()); list.add(carDto); log.info(entry.getKey() + " ;" + entry.getValue()); } EasyExcel.write(filename_new, CarDto.class).sheet("結果表").doWrite(list); }else { System.out.println("文件沒有該工作表,請重新檢查上傳"); } } else { System.out.println("文件為空,請重新上傳"); } } public Map<String,String> readExcel(ExeclDto execlDto){ // 讀取的excel文件路徑 String filename = execlDto.getFilename(); // 讀取excel File file = new File(filename); Workbook sheets = null; try { sheets = WorkbookFactory.create(file); } catch (IOException e) { e.printStackTrace(); } catch (InvalidFormatException e) { e.printStackTrace(); } Sheet sheetAt1 = sheets.getSheet(execlDto.getName1()); Sheet sheetAt2 = sheets.getSheet(execlDto.getName2()); //判斷excel表中是否有該工作表 if (sheetAt1 !=null && sheetAt2 !=null) { //採用LinkedHashMap保證數據的順序性 Map<String, Double> map1 = new LinkedHashMap<>(); Map<String, String> map2 = new LinkedHashMap<>(); //迴圈工作表行 for (Row row1 : sheetAt1) { //獲取工作表列值 String stringCellValue = row1.getCell(0).getStringCellValue(); //設置string類型初始閾值 map1.put("bz", 0.0); //迴圈需要比較的工作表列值 for (Row row2 : sheetAt2) { //獲取工作表列值 String stringCellValue1 = row2.getCell(0).getStringCellValue(); //判斷車輛款式,獲取字元串位置 if (stringCellValue.contains("款") && stringCellValue1.contains("款")) { int i = stringCellValue.indexOf("款"); int b = stringCellValue1.indexOf("款"); //進行款式截取並比較款式是否一致 if (stringCellValue.substring(i - 4, i).equals(stringCellValue1.substring(b - 4, b))) { //採用String裡面的方法進行相似度取值 double similarity = StringUtils.getJaroWinklerDistance(stringCellValue, stringCellValue1); //進行相似度比較 if (similarity > map1.get("bz")) { //相似度高的替換低的 map1.put("bz", similarity); //存放進map集合 map2.put(stringCellValue, stringCellValue1); } } } } } return map2; }else { return null; } } }