Java CSV 文件上传并且批量插入数据库

坑还是有点,特别是加spring事务,还有就是删除文件不稳定,还有接收参数时一些注解会造成误导,有些注解也是不能用 的,请慎重,只做参考(上传TXT文件)。

 

1.准备:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-csv -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.4</version>
</dependency>

2.工具类,使用CSV工具类,生成file文件

package com.rand.safc.common.comm.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 9043
 * @Date: 2020/07/30/15:50
 * @Description:
 */
public class CsvImportUtil {
    //上传文件的路径
    private final static URL PATH = Thread.currentThread().getContextClassLoader().getResource("");

    /**
     * @return File  一般文件类型
     * @Description 上传文件的文件类型
     * @Param multipartFile
     **/
    public static File uploadFile(MultipartFile multipartFile) {
        // 获 取上传 路径
        String path = PATH.getPath() + multipartFile.getOriginalFilename();
        try {
            // 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例
            File file = new File(path);
            // 此抽象路径名表示的文件或目录是否存在
            if (!file.getParentFile().exists()) {
                // 创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录
                file.getParentFile().mkdirs();
            }
            // 转换为一般file 文件
            multipartFile.transferTo(file);

            return file;
        } catch (IOException e) {

            e.printStackTrace();
            return null;
        }
    }
}

3.Controller

package com.soko.safc.admin.controller.promotion;

import com.rand.safc.common.comm.util.CsvImportUtil;
import com.rand.safc.common.model.promotion.SmsMarketing;
import com.rand.safc.common.service.promotion.SmsMarketingService;
import co
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值