SpringBoot项目读取CSV文件(下)

接上篇SpringBoot项目CSV文件NIO读取_思维穿梭的博客-CSDN博客

在CsvReaderBuilder类中添加类读取方法:

 public <T> List<T> toClassRead(T cla)  {
        if (inputStream == null){
            return new ArrayList<>();
        }
        if (rowNo < 0 ) {
            setRowNo(defaultRowNo);
        }
        List<String> rowList = new ArrayList<>();
        listener.setFileLength(fileLength);
        readFile();
        listener.doAfter();
        List<T> list = new LinkedList<>();
        Class clazz = cla.getClass();
        try {
            Constructor declaredConstructor = clazz.getDeclaredConstructor();

            Field[] declaredFields = clazz.getDeclaredFields();
            for (Object row: listener.getList().subList(rowNo, listener.getList().size())) {
                T o = (T) declaredConstructor.newInstance();
                List<Object> rowStr = (List<Object>)row;
                int size = rowStr.size();
                boolean noValue = true;
                for (Field field: declaredFields) {
                    CsvProperty csvProperty = field.getDeclaredAnnotation(CsvProperty.class);
                    if (null == csvProperty){
                        continue;
                    }
                    Object value = null;

                    int index = csvProperty.index();
                    if (index < size){
                        value = rowStr.get(index);
                    }
                    noValue = noValue && (value ==null);
                    field.setAccessible(true);
                    field.set(o, value);
                }
                // 过滤空行
                if (noValue){
                    continue;
                }
                list.add(o);
            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return list;
    }

对应的注解:

import java.lang.annotation.*;

/**
 * @author 四维穿梭
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface CsvProperty {

    String value() default "";

    int index() default -1;
}

对应的读取文件所要的实体类:

import com.ufc.dream.commons.csv.CsvProperty;
import lombok.Data;

@Data
public class TestBean {

    @CsvProperty(index = 0)
    private String zone;

    @CsvProperty(index = 1)
    private String name;
    @CsvProperty(index = 2)
    private String start;
    @CsvProperty(index = 3)
    private String end;
    @CsvProperty(index = 4)
    private String length;
}

使用方式():

    public static  void testToBean(){
        File file = new File("F:\\考勤\\csvFile.csv");
        try {
            FileInputStream inputStream = new FileInputStream(file);
            List<TestBean> objects = CsvReader
                    .read()
                    .setRowNo(1)
                    .setInputStream(inputStream)
                    .setFileLength(file.length()).setHead(new ArrayList<>())
                    .toClassRead(new TestBean());

            System.out.println(objects.size());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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、付费专栏及课程。

余额充值