/** * 读取CSV文件 * * @param filePath:文件路径 */ public static Map<String, List<String>> readCSVFileWithMap(URL filePath) throws Exception { URLConnection conn = filePath.openConnection(); CSVReader reader = new CSVReader(new InputStreamReader(conn.getInputStream())); Map<String, List<String>> map = new HashMap<>(); String[] nextLine; List<String> headerList = new ArrayList<>(); /* * 1、 读取到了第一行(表头行) * 2、 拆解数组,把内容放到list中 * 3、 把数据放到map中(key, null) tLength : 是用来记录你有多少列 * 4、 表格体的遍历 * 5、 两种情况 * 5.1 表头列数大于表格体(正常读) * 5.2 表头列数小于表格体(出现表头漏写) */ // 记录表格行数 int startRow = 0; // 记录表格列数 int tLength = 0; while ((nextLine = reader.readNext()) != null) { startRow++; if (startRow == 1) { for (int j = 0; j < nextLine.length; j++) { List<String> bodyList = new ArrayList<>(); headerList.add(nextLine[j]); map.put(nextLine[j], bodyList); if (StringUtils.isNotBlank(nextLine[j])) { tLength++; } } } else { /* 读取body * 1、 读取每一行 * 2、 正在遍历的是哪一列 * 3、 是不是问题列 * 4、 不是问题列,读取前一次map内对应列的value值 * 5、 加入当前值到value中 * 6、 再次put到map中 */ for (int k = 0; k < nextLine.length; k++) { if (tLength > k) { String key = headerList.get(k); List<String> list = map.get(key); list.add(nextLine[k]); map.put(key, list); } else { // 有额外列数 ,请检测表头行名 throw new ReaderException("reader:{}", "有额外的列数,请检测表头"); } } } } return map; }
通过url读取csv文件
最新推荐文章于 2024-05-29 22:56:42 发布