Java使用opencsv完成对csv批量操作

2024-02-13 17:20

本文主要是介绍Java使用opencsv完成对csv批量操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 前言
  • 一、maven
  • 二、造数
  • 三、代码部分
    • 1.OpenCsvController
    • 2.OpenCsvUtil
    • 3.StudentInfo
    • 4.CodeToValue
  • 三、效果展示
    • 1.download
    • 2.upload
  • 总结


前言

csv文件是不同于excel文件的另一种文件,常常以,作为分隔符,本篇将通过JavaBean的形式完成对csv文件的读取和写出等,包含了对日期类型和码值类型数据的处理替换,真正做到稍微修改即可用。


一、maven

<!-- https://mvnrepository.com/artifact/com.opencsv/opencsv --><dependency><groupId>com.opencsv</groupId><artifactId>opencsv</artifactId><version>5.7.1</version></dependency>

二、造数

数据的话我数据库里有了,这个步骤我就跳过了
在这里插入图片描述

三、代码部分

1.OpenCsvController

@RestController
@RequestMapping("opencsv")
public class OpenCsvController {@Autowiredprivate StudentInfoService studentInfoService;@GetMapping("/download")public void download(HttpServletResponse response) throws IOException {//List<List<Map<String, Object>>> testsp = testService.testsp();// 响应正文response.reset();response.setContentType("application/octet-stream");// 这里URLEncoder.encode可以防止中文乱码response.setHeader("Content-disposition", "attachment;filename=t_student_info.csv");StudentInfoExample studentInfoExample = new StudentInfoExample();studentInfoExample.setOrderByClause("CAST(id AS SIGNED)");List<StudentInfo> studentInfos = studentInfoService.selectByExample(studentInfoExample);OpenCsvUtil.beanToCsv(new OutputStreamWriter(response.getOutputStream(),"GBK"),studentInfos);}@RequestMapping("/upload")public void upload(MultipartFile file) throws IOException {OpenCsvUtil.csvToBean(file);}
}

2.OpenCsvUtil

public class OpenCsvUtil {public static void beanToCsv(Writer writer, List list) {CSVWriter csvWriter = null;try {csvWriter = new CSVWriter(writer,CSVWriter.DEFAULT_SEPARATOR,CSVWriter.NO_QUOTE_CHARACTER,CSVWriter.NO_ESCAPE_CHARACTER,CSVWriter.DEFAULT_LINE_END);// 映射策略/*有序的,自己组织头*/
//            String []header=new String[] {"学号","姓名","年龄","出生日期","民族","证件类型","证件号码","手机号","入学时间","家庭住址","院系","专业","班级","辅导员","是否在籍"};
//            String []mapping=new String[] {"id","name","age","birthday","nation","idType","idNumber","tel","admissionTime","address","faculty","major","classID","instructor","registered"};
//            mappingStrategy.setColumnMapping(mapping);
//            csvWriter.writeNext(header);
//            ColumnPositionMappingStrategy <StudentInfo> mappingStrategy = new ColumnPositionMappingStrategy();/*无序的,头从注解中获取*/HeaderColumnNameMappingStrategy<StudentInfo> mappingStrategy = new HeaderColumnNameMappingStrategy();mappingStrategy.setType(StudentInfo.class);mappingStrategy.generateHeader((StudentInfo)list.get(0));StatefulBeanToCsv<StudentInfo> statefulBeanToCsv = new StatefulBeanToCsvBuilder<StudentInfo>(csvWriter).withMappingStrategy(mappingStrategy).build();statefulBeanToCsv.write(list);} catch (CsvRequiredFieldEmptyException e) {throw new RuntimeException(e);} catch (CsvDataTypeMismatchException e) {throw new RuntimeException(e);} finally {if (writer != null) {try {writer.close();} catch (IOException e) {e.printStackTrace();}}}}public static void csvToBean(MultipartFile file) {CSVReader reader = null;try {reader = new CSVReader(new InputStreamReader(file.getInputStream(), "GBK"));HeaderColumnNameMappingStrategy<StudentInfo> mappingStrategy = new HeaderColumnNameMappingStrategy();mappingStrategy.setType(StudentInfo.class);CsvToBean<StudentInfo> build = new CsvToBeanBuilder<StudentInfo>(reader).withType(StudentInfo.class).build();build.setMappingStrategy(mappingStrategy);List<StudentInfo> beans = build.parse();beans.forEach(System.out::println);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (reader != null) {reader.close();}} catch (IOException e) {e.printStackTrace();}}}
}

3.StudentInfo

public class StudentInfo implements Serializable {private static final long serialVersionUID = 1L;/** 学号 **/@ApiModelProperty(value = "学号")@CsvBindByName(column="学号")@CsvBindByPosition(position = 0)private String id;/** 姓名 **/@ApiModelProperty(value = "姓名")@CsvBindByName(column="姓名")@CsvBindByPosition(position = 1)private String name;/** 年龄 **/@ApiModelProperty(value = "年龄")@CsvBindByName(column="年龄")@CsvBindByPosition(position = 2)private Integer age;/** 出生日期 **/@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")@ApiModelProperty(value = "出生日期")@CsvBindByName(column="出生日期")@CsvDate("yyyy年MM月dd日")private Date birthday;/** 民族 **/@ApiModelProperty(value = "民族")@CsvBindByName(column="民族")private String nation;/** 证件类型 **/@ApiModelProperty(value = "证件类型")@CsvBindByName(column="证件类型")private String idType;/** 证件号码 **/@ApiModelProperty(value = "证件号码")@CsvBindByName(column="证件号码")private String idNumber;/** 手机号 **/@ApiModelProperty(value = "手机号")@CsvBindByName(column="手机号")private Integer tel;/** 入学时间 **/@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")@ApiModelProperty(value = "入学时间")@CsvDate("yyyy年MM月dd日 HH:mm:ss")@CsvBindByName(column="入学时间")private Date admissionTime;/** 家庭住址 **/@ApiModelProperty(value = "家庭住址")@CsvBindByName(column="家庭住址")private String address;/** 院系 **/@ApiModelProperty(value = "院系")@CsvBindByName(column="院系")private String faculty;/** 专业 **/@ApiModelProperty(value = "专业")@CsvBindByName(column="专业")private String major;/** 班级 **/@ApiModelProperty(value = "班级")@CsvBindByName(column="班级")private Integer classID;/** 辅导员 **/@ApiModelProperty(value = "辅导员")@CsvBindByName(column="辅导员")private String instructor;/** 是否在籍(0:否;1:是) **/@ApiModelProperty(value = "是否在籍(0:否;1:是)")@CsvCustomBindByName(column="是否在籍",converter = CodeToValue.class)private Character registered;/** 分数信息**/@ApiModelProperty(value = "分数信息StudentScore")private ArrayList<StudentScore> studentScore;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getNation() {return nation;}public void setNation(String nation) {this.nation = nation;}public String getIdType() {return idType;}public void setIdType(String idType) {this.idType = idType;}public String getIdNumber() {return idNumber;}public void setIdNumber(String idNumber) {this.idNumber = idNumber;}public Integer getTel() {return tel;}public void setTel(Integer tel) {this.tel = tel;}public Date getAdmissionTime() {return admissionTime;}public void setAdmissionTime(Date admissionTime) {this.admissionTime = admissionTime;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public String getFaculty() {return faculty;}public void setFaculty(String faculty) {this.faculty = faculty;}public String getMajor() {return major;}public void setMajor(String major) {this.major = major;}public Integer getClassID() {return classID;}public void setClassID(Integer classID) {this.classID = classID;}public String getInstructor() {return instructor;}public void setInstructor(String instructor) {this.instructor = instructor;}public Character getRegistered() {return registered;}public void setRegistered(Character registered) {this.registered = registered;}public ArrayList<StudentScore> getStudentScore() {return studentScore;}public void setStudentScore(ArrayList<StudentScore> studentScore) {this.studentScore = studentScore;}public StudentInfo() {super();}public StudentInfo(String id, String name, Integer age, Date birthday, String nation, String idType, String idNumber, Integer tel, Date admissionTime, String address, String faculty, String major, Integer classID, String instructor, Character registered) {this.id = id;this.name = name;this.age = age;this.birthday = birthday;this.nation = nation;this.idType = idType;this.idNumber = idNumber;this.tel = tel;this.admissionTime = admissionTime;this.address = address;this.faculty = faculty;this.major = major;this.classID = classID;this.instructor = instructor;this.registered = registered;}@Overridepublic String toString() {return "StudentInfo{" +"id=" + id +", name='" + name + '\'' +", age=" + age +", birthday=" + birthday +", nation='" + nation + '\'' +", idType='" + idType + '\'' +", idNumber='" + idNumber + '\'' +", tel=" + tel +", admissionTime=" + admissionTime +", address='" + address + '\'' +", faculty='" + faculty + '\'' +", major='" + major + '\'' +", classID=" + classID +", instructor='" + instructor + '\'' +", registered=" + registered +", studentScore=" + studentScore +'}';}
}

4.CodeToValue

public class CodeToValue extends AbstractBeanField {@Overrideprotected Object convert(String s) throws CsvDataTypeMismatchException, CsvConstraintViolationException {if(s.equals("否")){return  '0';}if(s.equals("是")){return  '1';}return null;}@Overridepublic String convertToWrite(Object value) {if(String.valueOf(value).equals("0")){return  "否";}if(String.valueOf(value).equals("1")){return  "是";}return null;}
}

三、效果展示

1.download

在这里插入图片描述

2.upload

在这里插入图片描述


总结

回到顶部
官方网站
快速入门
操作excel点这里

这篇关于Java使用opencsv完成对csv批量操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/706139

相关文章

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.