原创

上传或导入CSV文件

1.springmvc 使用MultipartFile上传文件

public List<PoBom> readCsv(MultipartFile file){
        List<PoBom> list = new ArrayList<PoBom>();

        if (!file.isEmpty()){
            InputStreamReader isr = null;
            BufferedReader br = null;
            try {
                isr = new InputStreamReader(file.getInputStream());
                br = new BufferedReader(isr);
                String line = null;
                List<List<String>> strs = new ArrayList<List<String>>();
                while ((line = br.readLine()) != null){
                    strs.add(Arrays.asList(line.split(",")));
                }
                JSONArray array = toJsonArray(strs);
                list = array.toJavaList(PoBom.class);
                System.out.println(list);
            } catch (IOException e) {
                //
                e.printStackTrace();
            }finally {
                try {
                    if (br != null){
                        br.close();
                    }
                    if (isr != null){
                        isr.close();
                    }
                } catch (IOException e) {
                    //
                    e.printStackTrace();
                }
            }

        }else {
            //

        }
        return list;
    }
    //fastjson
    private JSONArray toJsonArray(List<List<String>> strs){
        JSONArray array = new JSONArray();
        for (int i = 1; i < strs.size(); i++) {
            JSONObject object = new JSONObject();
            for (int j = 0; j < strs.get(0).size(); j++) {
                object.put(strs.get(0).get(j),strs.get(i).get(j));
            }
            array.add(object);
        }
        return array;
    }

2.读取本地.CSV文件

public String importFileCsv(MultipartFile multipartFile) throws  Exception{


        String fielname = multipartFile.getOriginalFilename();
        String path ="D://"+fielname;
        File file1 = new File(path);
        //复制文件
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file1);
       //获取文件
        File file2 = new File(path);
        FileReader fReader = new FileReader(file2);
        CSVReader csvReader = new CSVReader(fReader);
        String[] strs = csvReader.readNext();

        if(strs != null && strs.length > 0){
            if(strs.length != 5){
                return "表头应为5列";
            }
        }

        List<String[]> list = csvReader.readAll();
        for(String[] ss : list) {
            if (ss.length == 5) {
            //判断数据库中是否有

                     }
                     //业务代码
                    }

        csvReader.close();

        return "上传成功";

    }
正文到此结束
本文目录