java实现解析csv文件方法二:解析csv文件并转成bean

Posted 巴适的哼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java实现解析csv文件方法二:解析csv文件并转成bean相关的知识,希望对你有一定的参考价值。

1.pom.xml引入jar包

       <!--csv-->
        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>4.4</version>
        </dependency>

2.重写映射规则

public class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {

    @Override
    public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
        super.setColumnMapping(new String[ FieldUtils.getAllFields(bean.getClass()).length]);
        final int numColumns = findMaxFieldIndex();
        if (!isAnnotationDriven() || numColumns == -1) {
            return super.generateHeader(bean);
        }

        String[] header = new String[numColumns + 1];

        BeanField beanField;
        for (int i = 0; i <= numColumns; i++) {
            beanField = findField(i);
            String columnHeaderName = extractHeaderName(beanField);
            header[i] = columnHeaderName;
        }
        return header;
    }

    private String extractHeaderName(final BeanField beanField) {
        if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0) {
            return StringUtils.EMPTY;
        }

        final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
        return bindByNameAnnotation.column();
    }
}

3.实体类(bean)添加注解 @CsvBindByPosition 和 @CsvBindByName

public class WftTestEntity implements Serializable{
    private static final long serialVersionUID = 1L;
    /**
     *交易时间
     */
    @CsvBindByPosition(position = 0)
    @CsvBindByName(column = "交易时间")
    private String test1;


    /**
     *公众账号ID
     */
    @CsvBindByPosition(position = 1)
    @CsvBindByName(column = "公众账号ID")
    private String test2;
public String getTest1() { return test1; } public void setTest1(String test1) { this.test1 = test1; } public String getTest2() { return test2; } public void setTest2(String test2) { this.test2 = test2; } }

4.解析并转换为bean

4.1:单一的转换(非泛型)

     /**
     * 解析csv文件并转成bean
     * @return
     * @throws IOException
     */
    public static List<WftTestEntity> getWftTestEntityList(String fileName) throws IOException{
        InputStreamReader is = new InputStreamReader(new  FileInputStream(fileName),"GBK");
        HeaderColumnNameMappingStrategy<WftTestEntity> mappingStrategy = new HeaderColumnNameMappingStrategy<>();
        mappingStrategy.setType(WftTestEntity.class);
        CsvToBean<WftTestEntity> build = new CsvToBeanBuilder<WftTestEntity>(is).withMappingStrategy(mappingStrategy).withQuoteChar(‘`‘).withSeparator(‘"‘).withSeparator(‘,‘).withSeparator(‘"‘).build();
        List<WftTestEntity> wftTestEntityList = build.parse();
        return wftTestEntityList;
    }

4.2:通用的转换(泛型)

  

    /**
     * 解析csv文件并转成bean
     * @param fileName
     * @param clazz
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> List<T> getCsvData(String fileName, Class<T> clazz) throws IOException{
        InputStreamReader is = new InputStreamReader(new  FileInputStream(fileName),"gbk");

        HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
        strategy.setType(clazz);

        CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(is)
                .withSeparator(‘,‘)
                .withQuoteChar(‘‘‘)
                .withMappingStrategy(strategy).build();
        return csvToBean.parse();
    }

5.调用测试mian

public static void main(String[] args) throws IOException{

//调用
List<WftTestEntity> wftTestEntities = getWftTestEntityList("路径+csv文件名");
List<WftTestEntity> wftTestEntityList = getCsvData("路径+csv文件名",WftTestEntity.class);
}

  

 

以上是关于java实现解析csv文件方法二:解析csv文件并转成bean的主要内容,如果未能解决你的问题,请参考以下文章

java怎么读写创建csv文件

使用Java开发 接收一个Json文件,然后解析Json 并按照特定的Csv格式转换,输出Csv格式的文件,求案例谢谢

java对操作csv文件

如何用Java解析CSV文件

Java:使用OpenCSV解析CSV文件

CSV文件规范及其Java解析方式