springboot 将数据保存到csv文件和读取csv文件并恢复数据

  1. 引入依赖
<!-- csv依赖 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.7</version>
</dependency>
<!-- 上传工具依赖 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>
  1. 创建csv工具类CsvImportUtil

上传文件方法(将multipartFile转换为file):

/**
     * @return File  一般文件类型
     * @Description 上传文件的文件类型
     * @Param multipartFile
     **/
    public static File uploadFile(MultipartFile multipartFile) {
    //获取自己要上传文件的路径(这个自己改动)
        Path_entity path_entity= csvImportUtil.pathMapper.upload_path();
        String PATH = path_entity.getCatalogue();
        String path = PATH+"/"+multipartFile.getOriginalFilename();
        log.info(path); //拿到最终上传路径
        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;
        }

    }

读取CSV文件的内容:

/**
     * @return List<List<String>>
     * @Description 读取CSV文件的内容(不含表头)
     * @Param filePath 文件存储路径,colNum 列数
     **/
    public static List<List<String>> readCSV(String filePath, int colNum) {
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        FileInputStream fileInputStream = null;

        try {
            fileInputStream = new FileInputStream(filePath);
            inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            bufferedReader = new BufferedReader(inputStreamReader);

            CSVParser parser = CSVFormat.DEFAULT.parse(bufferedReader);


            //  表内容集合,外层 List为行的集合,内层 List为字段集合
            List<List<String>> values = new ArrayList<>();


            int rowIndex = 0;
            // 读取文件每行内容

            for (CSVRecord record : parser.getRecords()) {
                //  跳过表头
                if (rowIndex == 0) {
                    rowIndex++;
                    continue;
                }
                // 判断下角标是否越界
                if (colNum > record.size()) {
                    // 返回空集合
                    return values;
                }
                //  每行的内容
                List<String> value = new ArrayList<>();
                for (int i = 0; i < colNum; i++) {
                    value.add(record.get(i));
                }
                values.add(value);
                rowIndex++;
            }
            return values;
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            //关闭流
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
  1. 生成csv文件
public String CSV_file(HttpServletResponse response,String mindId) {
        List<Map<String, Object>> dataList = null;

        Mind mind = mindMapper.get_mind_id(mindId);// 查询到要导出的信息
        //表头
        String sTitle = "id,user,mindName,mindData,mindOptions";
        String fName = "mind_";
        String mapKey = "id,user,mindName,mindData,mindOptions";
        dataList = new ArrayList<>();
        Map<String, Object> map = null;

            map = new HashMap<>();

            map.put("id", mind.getMindId());
            map.put("user",mind.getUser());
            map.put("mindName", mind.getMindName());
            String str=mind.getMindData();
            String minddata=str;
        //先判断字符里是否含有逗号
        if(str.contains(",")){
            //如果还有双引号,先将双引号转义,避免两边加了双引号后转义错误
            if(str.contains("\"")){
                minddata=str.replace("\"", "\"\"");
            }
            //将逗号转义
            minddata="\""+minddata+"\"";
        }
            map.put("mindData",minddata);
            map.put("mindOptions",mind.getMindOptions());

            dataList.add(map);

        try (final OutputStream os = response.getOutputStream()) {
            ExportUtil.responseSetProperties(fName, response);
            ExportUtil.doExport(dataList, sTitle, mapKey, os);
            return null;
        } catch (Exception e) {
            log.error("生成csv文件失败", e);
        }
        return "生成csv文件失败";
    }
  1. 读取csv文件
public Object CSV_file( MultipartFile file) {
        // 使用CSV工具类,生成file文件
        File csvFile = CsvImportUtil.uploadFile(file);
        // 将文件内容解析,存入List容器,List<String>为每一行内容的集合,6为CSV文件每行的总列数
       List<List<String>> lists = CsvImportUtil.readCSV(csvFile.getPath(), 5);
        if(lists != null ){
            List<String> list=lists.get(0);
            Mind mind=new Mind();
            mind.setMindId(list.get(0));
            mind.setUser(list.get(1));
            mind.setMindName(list.get(2));
            mind.setMindData(list.get(3));
            mind.setMindOptions(list.get(4));
            csvFile.delete();
            return mind;
        }
        return "打开文件失败";

    }
在Spring Boot中读取CSV文件进行数据映射,可以使用OpenCSV库。以下是实现步骤: 1. 添加OpenCSV依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.0</version> </dependency> ``` 2. 创建CSV文件读取器 创建一个CSV文件读取器,使用OpenCSV库的CSVReader类。该类提供了多种方法用于读取CSV文件中的数据。 ``` @Service public class CsvReaderService { public List<Employee> readEmployeesFromCsv(String filePath) throws IOException { List<Employee> employees = new ArrayList<>(); FileReader fileReader = new FileReader(filePath); CSVReader csvReader = new CSVReaderBuilder(fileReader).withSkipLines(1).build(); String[] line; while ((line = csvReader.readNext()) != null) { Employee employee = new Employee(); employee.setId(Integer.parseInt(line[0])); employee.setName(line[1]); employee.setAge(Integer.parseInt(line[2])); employee.setSalary(Double.parseDouble(line[3])); employees.add(employee); } csvReader.close(); return employees; } } ``` 在上述代码中,我们首先创建了一个CSVReader对象,然后使用while循环逐行读取CSV文件中的数据将其映射到Employee对象中。在每次迭代中,我们将Employee对象添加到employees列表中,在最后关闭CSVReader对象。 3. 创建实体类 创建一个Employee实体类,用于将CSV文件中的数据映射到对象中。 ``` public class Employee { private int id; private String name; private int age; private double salary; // getters and setters } ``` 4. 使用CsvReaderService类读取CSV文件 在需要读取CSV文件的地方,注入CsvReaderService类调用readEmployeesFromCsv方法。 ``` @Autowired private CsvReaderService csvReaderService; public void processCsvFile() throws IOException { List<Employee> employees = csvReaderService.readEmployeesFromCsv("employees.csv"); // Do something with employees } ``` 以上就是Spring Boot项目读取CSV文件进行数据映射的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值