package com.besttop.logistics.util; import org.apache.http.entity.ContentType; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.util.*; public class CsvUtil { public static void main(String[] args) throws IOException { InputStream inputStream = null; MultipartFile multipartFile = null; try { inputStream = new FileInputStream("D:\\会计科目.csv"); File file = new File("会计科目"); multipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream); } catch (FileNotFoundException e) { e.printStackTrace(); } List<Map<String,String>> list = null; try { list = readCSV(multipartFile); } catch (Exception e) { e.printStackTrace(); } //遍历解析出来的list for (Map<String,String> map : list) { for (Map.Entry<String,String> entry : map.entrySet()) { System.out.print(entry.getKey()+":"+entry.getValue()+","); } System.out.println(); } } public static List<Map<String,String>> readCSV(MultipartFile file) throws UnsupportedEncodingException, IOException, Exception { Reader read = new InputStreamReader(file.getInputStream(), "UTF-8"); BufferedReader bReader = new BufferedReader(read); List<Map<String,String>> list = new ArrayList<>(); int i = 0; while (true) { String line = bReader.readLine(); if (line == null) { break; } if (i > 0) {// 第一行标题不转换 String[] arrStr = line.split(","); //将一行数据转化为一个对象 List<String> arrList = Arrays.asList(arrStr); String row = null; Map<String,String> map = new HashMap<>(); for (int j = 0; j<arrList.size(); j++) { row = arrList.get(j); if(row !=null){ if ( j < arrList.size()) { map.put(j+"", arrList.get(j)); } }else{ break; } } list.add(map); } i++; } return list; } }
csv文件解析
最新推荐文章于 2024-05-26 00:15:00 发布