上传csv文件并解析

思路:先将csv文件上传到本地路径后,然后进行读取解析,可删除可不删除

示例代码:

1、上传文件到本地

		MultipartFile file = null; //上传的文件,直接从方法参数中获取
        if (file == null) {
            throw new RuntimeException("文件为空");
        }

        String fileName = file.getOriginalFilename();
        String prefixName = fileName.substring(0, fileName.lastIndexOf("."));
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        if (!".csv".equals(suffixName)) {
            throw new RuntimeException("上传文件格式需要是csv文件");
        }

        FileOutputStream outputStream = null;
        InputStream inputStream = null;
        String nowDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String batchId = UUID.randomUUID().toString(); //可以加入随机字符串
        String uploadFileName = prefixName + "-" + batchId + suffixName; //rename file
        String filePath="";//自定义文件存放路径
        File f = new File(filePath + File.separator + nowDate + File.separator + uploadFileName);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }

        try {
            outputStream = new FileOutputStream(f);
            inputStream = file.getInputStream();
            byte[] bytes = new byte[5125];
            int i = -1;
            while ((i = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, i);
            }
            outputStream.flush();

            log.info("uploadedFile {}  ....... success", f.getPath());
            return f.getPath();
        } catch (Exception e) {
            log.error("Upload file fail", e);
            throw new RuntimeException("上传数据失败, 请修改后重新上传, " + e.getMessage());
        } finally {
            try {
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
            }
        }

此处采用的文件流是自己捕获异常,关闭输入和输出流的,jdk8中可以直接使用try()catch{},如果{}中的代码出项了异常,()中的资源就会被关闭,这在inputstream和outputstream的使用中会很方便。

2、按指定路径解析csv文件内容,可变换csv表头字段的顺序

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.7</version>
</dependency>
        String filePath ="";//上传后的文件全路径
        BufferedReader bufferedReader;
        try {
            InputStreamReader fileReader = new InputStreamReader(new FileInputStream(filePath), "GBK");
            bufferedReader = new BufferedReader(fileReader);
        } catch (Exception e) {
            throw new RuntimeException("read file error!");
        }

        Iterator<CSVRecord> iterator = null;
        try {
            iterator = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(bufferedReader).iterator();
        } catch (IOException e) {
            return Result.fail("format trade file error");
        }
        int lineCount = 1;
        while (iterator.hasNext()) {
            try {
                lineCount = lineCount + 1;  //可以通过记录行数提示哪一行有问题
                CSVRecord csvRecord = iterator.next();
                Map<String, String> map = csvRecord.toMap();

                String userName = map.get("userName"); //可以直接通过map获取文件列
                String tradeType = map.get("tradeType");
                BigDecimal amount = new BigDecimal(map.get("amount"));
                BigDecimal price = new BigDecimal(map.get("price"));
                BigDecimal qty = new BigDecimal(map.get("qty"));
                BigDecimal fee = new BigDecimal(map.get("fee"));
            } catch (Exception e) {
                log.error("process trade record file error: {}", e);
                return Result.fail("上传文件失败,请重新上传!");
            }
        }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要实现上 CSV 文件并在 Vue 中解析并显示数据,你可以按照以下步骤进行操作: 1. 安装 `papaparse` 库 ``` npm install papaparse --save ``` 2. 在 Vue 组件中引入 `papaparse` ```javascript import Papa from 'papaparse'; ``` 3. 在 Vue 组件中定义一个 data 属性用来存储上CSV 文件解析后的数据 ```javascript data() { return { file: null, csvData: null }; }, ``` 4. 在 Vue 模板中添加一个文件组件和一个解析按钮 ```html <template> <div> <input type="file" @change="handleFileUpload"> <button @click="parseCSV">解析</button> <table v-if="csvData"> <thead> <tr> <th v-for="(value, key) in csvData[0]" :key="key">{{ key }}</th> </tr> </thead> <tbody> <tr v-for="(row, index) in csvData" :key="index"> <td v-for="(value, key) in row" :key="key">{{ value }}</td> </tr> </tbody> </table> </div> </template> ``` 5. 在 Vue 组件中定义一个方法用来处理文件事件,并将上文件存储在 `file` 属性中 ```javascript methods: { handleFileUpload(event) { this.file = event.target.files[0]; } } ``` 6. 在 Vue 组件中定义一个方法用来解析CSV 文件 ```javascript methods: { parseCSV() { Papa.parse(this.file, { header: true, complete: (results) => { this.csvData = results.data; } }); } } ``` 7. 当用户点击解析按钮时,调用 `parseCSV` 方法解析CSV 文件,并将结果存储在 `csvData` 属性中,在表格中显示解析后的数据。 这样,用户上 CSV 文件后,可以点击解析按钮将其解析并在表格中显示。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码厚炮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值