excel导入

  1. public static List<Map<String,Object>> test1() throws Exception{
  2. File file = new File("C:/Users/luo_a/Desktop/数据测试.xlsx");
  3. if (!file.exists()){
  4. throw new Exception("文件不存在!");
  5. }
  6. InputStream in = new FileInputStream(file);
  7.  
  8. // 读取整个Excel
  9. XSSFWorkbook sheets = new XSSFWorkbook(in);
  10. // 获取第一个表单Sheet
  11. XSSFSheet sheetAt = sheets.getSheetAt(0);
  12. //默认第一行为标题行,i = 0
  13. XSSFRow titleRow = sheetAt.getRow(0);
  14. List<Map<String,Object>> mapList = new ArrayList<>();
  15. // 循环获取每一行数据
  16. for (int i = 1; i < sheetAt.getPhysicalNumberOfRows(); i++) {
  17. XSSFRow row = sheetAt.getRow(i);
  18. // 读取每一列内容
  19. Map<String,Object> map = new HashMap<>();
  20. for (int index = 0; index < row.getPhysicalNumberOfCells(); index++) {
  21. XSSFCell titleCell = titleRow.getCell(index);
  22. XSSFCell cell = row.getCell(index);
  23. cell.setCellType(CellType.STRING);
  24. if (cell.getStringCellValue().equals("")) {
  25. continue;
  26. }
  27. //表头数据
  28. String titleName = titleCell.getStringCellValue();
  29. //单元格内容
  30. String valueName = cell.getStringCellValue();
  31. //每一行的数据
  32. map.put(titleName,valueName);
  33. }
  34. mapList.add(map);
  35. }
  36. System.out.println(JSON.toJSONString(mapList));
  37. return mapList;
  38. }
posted @ 2023-02-14 09:58  张安东  阅读(29)  评论(0编辑  收藏  举报