java csv

作者: 虾米咬小米 | 来源:发表于2020-11-20 10:11 被阅读0次

    java csv 官网

    添加maven 依赖:

    <dependency>
        <groupId>net.sourceforge.javacsv</groupId>
        <artifactId>javacsv</artifactId>
        <version>2.0</version>
    </dependency>
    
    
    • 通过 javacsv生成 CSV 文件
    
    public class ReadAndWriterCsvFlie {
    
        // 需要写入的 csv 文件路径
        public static final String WRITE_CSV_FILE_PATH = "/Users/a123123/Work/flink-study/write_test.csv";
    
        /**
         * 生成 csv 文件
         */
        public static void writeCsvFile(String writeCsvFilePath) {
            // 创建 CSV Writer 对象, 参数说明(写入的文件路径,分隔符,编码格式)
            CsvWriter csvWriter = new CsvWriter(writeCsvFilePath,',', Charset.forName("GBK"));
    
            try {
                // 定义 header 头
                String[] headers = {"订单号", "用户名", "支付金额"};
                // 写入 header 头
                csvWriter.writeRecord(headers);
    
                // 写入一千条记录
                for (int i = 0; i < 1000; i++) {
                    String orderNum = UUID.randomUUID().toString();
                    String userName = "用户" + i;
                    String payMoney = String.valueOf(i);
    
                    // 写入行
                    csvWriter.writeRecord((String[]) Arrays.asList(orderNum, userName, payMoney).toArray());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                csvWriter.close();
            }
        }
    
        public static void main(String[] args) {
            writeCsvFile(WRITE_CSV_FILE_PATH);
        }
    }
    
    
    • 读取 csv 文件 , 直接读csv
    public class ReadAndWriterCsvFlie {
    
        // 需要写入的 csv 文件路径
        public static final String WRITE_CSV_FILE_PATH = "/Users/a123123/Work/flink-study/write_test.csv";
    
        /**
         * 读取 csv 文件
         */
        public static void readCsvFile(String readCsvFilePath) {
            // 缓存读取的数据
            List<String[]> content = new ArrayList<>();
    
            try {
                // 创建 CSV Reader 对象, 参数说明(读取的文件路径,分隔符,编码格式)
                CsvReader csvReader = new CsvReader(readCsvFilePath, ',', Charset.forName("GBK"));
                // 跳过表头
                csvReader.readHeaders();
    
                // 读取除表头外的内容
                while (csvReader.readRecord()) {
                    // 读取一整行
                    String line = csvReader.getRawRecord();
                    System.out.println(line);
    
                    content.add(csvReader.getValues());
                }
                csvReader.close();
    
                for (int row = 0; row < content.size(); row++) {
                    // 读取第 row 行,第 0 列的数据
                    String orderNum = content.get(row)[0];
                    System.out.println("==> orderNum: " + orderNum);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) {
            readCsvFile(WRITE_CSV_FILE_PATH);
        }
    }
    
    
    • 读取 csv 文件 , 通过接口的 MultipartFile
      public boolean importFile(MultipartFile multipartFile) {
    
            if (multipartFile.isEmpty()) throw new BusinessException("上传内容为空");
            boolean successful;
            try {
    
                // 用来保存数据
                ArrayList<String[]> csvFileList = new ArrayList<String[]>();
                List<ThjlEntity> tempList = new ArrayList<>();
                // 创建CSV读对象 例如:CsvReader(文件路径,分隔符,编码格式);
                CsvReader reader = new CsvReader(multipartFile.getInputStream(), ',', Charset.forName("GB2312"));
                // 跳过表头 如果需要表头的话,这句可以忽略
                reader.readHeaders();
                // 逐行读入除表头的数据
                while (reader.readRecord()) {
                    System.out.println(reader.getRawRecord());
                    String s = reader.get(0);
                    csvFileList.add(reader.getValues());
    
                    ThjlEntity thjlEntity = new ThjlEntity();
                    thjlEntity.setThsj(reader.get(0));
                    thjlEntity.setYhhm(reader.get(1));
                    thjlEntity.setBdxm(reader.get(2));
                    thjlEntity.setBdsfz(reader.get(3));
                    thjlEntity.setBddz(reader.get(4));
                    thjlEntity.setYhgsd(reader.get(5));
                    thjlEntity.setImei(reader.get(6));
                    thjlEntity.setDfhm(reader.get(7));
                    thjlEntity.setDdxm(reader.get(8));
                    thjlEntity.setDdsfz(reader.get(9));
                    thjlEntity.setDddz(reader.get(10));
                    thjlEntity.setDdgsd(reader.get(11));
                    thjlEntity.setHjlx(reader.get(12));
                    thjlEntity.setThsc(reader.get(13));
                    thjlEntity.setThszd(reader.get(14));
                    thjlEntity.setLac(reader.get(15));
                    thjlEntity.setCi(reader.get(16));
                    thjlEntity.setJd(reader.get(17));
                    thjlEntity.setWd(reader.get(18));
                    thjlEntity.setJzdz(reader.get(19));
    
    
                    tempList.add(thjlEntity);
    
                }
                reader.close();
    
    
                 successful = this.saveBatch(tempList);
    
            } catch (Exception e) {
                log.error("系统异常",e);
                throw new BusinessException(e.getMessage());
            }
    
            return successful;
        }
    
    • csv 模板下载
     @GetMapping("/download")
        public void download(HttpServletResponse response) throws Exception {
                try {
                    String path = "C:\\Users\\zpf\\Desktop\\1_220专案(1)_通话记录_话单.csv";
    
                    /**
                     * 写入csv结束,写出流
                     */
                    File tempFile = new File(path);
                    OutputStream out = response.getOutputStream();
                    byte[] b = new byte[10240];
                    File fileLoad = new File(tempFile.getCanonicalPath());
                    response.reset();
                    response.setContentType("application/csv");
                    response.setHeader("content-disposition", "attachment; filename=通话记录模板.csv");
                    long fileLength = fileLoad.length();
                    String length1 = String.valueOf(fileLength);
                    response.setHeader("Content_Length", length1);
                    FileInputStream in = new FileInputStream(fileLoad);
                    int n;
                    while ((n = in.read(b)) != -1) {
                        out.write(b, 0, n); //每次写入out1024字节
                    }
                    in.close();
                    out.close();
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    

    参考:https://juejin.im/post/6844904114690719752

    相关文章

      网友评论

          本文标题:java csv

          本文链接:https://www.haomeiwen.com/subject/xffdiktx.html