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

相关文章

golang1.23版本之前 Timer Reset方法无法正确使用

《golang1.23版本之前TimerReset方法无法正确使用》在Go1.23之前,使用`time.Reset`函数时需要先调用`Stop`并明确从timer的channel中抽取出东西,以避... 目录golang1.23 之前 Reset ​到底有什么问题golang1.23 之前到底应该如何正确的

SpringBoot项目中Maven剔除无用Jar引用的最佳实践

《SpringBoot项目中Maven剔除无用Jar引用的最佳实践》在SpringBoot项目开发中,Maven是最常用的构建工具之一,通过Maven,我们可以轻松地管理项目所需的依赖,而,... 目录1、引言2、Maven 依赖管理的基础概念2.1 什么是 Maven 依赖2.2 Maven 的依赖传递机

SpringBoot实现动态插拔的AOP的完整案例

《SpringBoot实现动态插拔的AOP的完整案例》在现代软件开发中,面向切面编程(AOP)是一种非常重要的技术,能够有效实现日志记录、安全控制、性能监控等横切关注点的分离,在传统的AOP实现中,切... 目录引言一、AOP 概述1.1 什么是 AOP1.2 AOP 的典型应用场景1.3 为什么需要动态插

详解Vue如何使用xlsx库导出Excel文件

《详解Vue如何使用xlsx库导出Excel文件》第三方库xlsx提供了强大的功能来处理Excel文件,它可以简化导出Excel文件这个过程,本文将为大家详细介绍一下它的具体使用,需要的小伙伴可以了解... 目录1. 安装依赖2. 创建vue组件3. 解释代码在Vue.js项目中导出Excel文件,使用第三

Linux alias的三种使用场景方式

《Linuxalias的三种使用场景方式》文章介绍了Linux中`alias`命令的三种使用场景:临时别名、用户级别别名和系统级别别名,临时别名仅在当前终端有效,用户级别别名在当前用户下所有终端有效... 目录linux alias三种使用场景一次性适用于当前用户全局生效,所有用户都可调用删除总结Linux

Java实现Excel与HTML互转

《Java实现Excel与HTML互转》Excel是一种电子表格格式,而HTM则是一种用于创建网页的标记语言,虽然两者在用途上存在差异,但有时我们需要将数据从一种格式转换为另一种格式,下面我们就来看看... Excel是一种电子表格格式,广泛用于数据处理和分析,而HTM则是一种用于创建网页的标记语言。虽然两

java图像识别工具类(ImageRecognitionUtils)使用实例详解

《java图像识别工具类(ImageRecognitionUtils)使用实例详解》:本文主要介绍如何在Java中使用OpenCV进行图像识别,包括图像加载、预处理、分类、人脸检测和特征提取等步骤... 目录前言1. 图像识别的背景与作用2. 设计目标3. 项目依赖4. 设计与实现 ImageRecogni

Java中Springboot集成Kafka实现消息发送和接收功能

《Java中Springboot集成Kafka实现消息发送和接收功能》Kafka是一个高吞吐量的分布式发布-订阅消息系统,主要用于处理大规模数据流,它由生产者、消费者、主题、分区和代理等组件构成,Ka... 目录一、Kafka 简介二、Kafka 功能三、POM依赖四、配置文件五、生产者六、消费者一、Kaf

Java访问修饰符public、private、protected及默认访问权限详解

《Java访问修饰符public、private、protected及默认访问权限详解》:本文主要介绍Java访问修饰符public、private、protected及默认访问权限的相关资料,每... 目录前言1. public 访问修饰符特点:示例:适用场景:2. private 访问修饰符特点:示例:

python管理工具之conda安装部署及使用详解

《python管理工具之conda安装部署及使用详解》这篇文章详细介绍了如何安装和使用conda来管理Python环境,它涵盖了从安装部署、镜像源配置到具体的conda使用方法,包括创建、激活、安装包... 目录pytpshheraerUhon管理工具:conda部署+使用一、安装部署1、 下载2、 安装3