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点这里

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/471866.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2024.2.15 模拟实现 RabbitMQ —— 消息持久化

目录 引言 约定存储方式 消息序列化 重点理解 针对 MessageFileManager 单元测试 小结 引言 问题&#xff1a; 关于 Message&#xff08;消息&#xff09;为啥在硬盘上存储&#xff1f; 回答&#xff1a; 消息操作并不涉及到复杂的增删查改消息数量可能会非常多&#xff…

【机器学习笔记】8 决策树

决策树原理 决策树是从训练数据中学习得出一个树状结构的模型。 决策树属于判别模型。 决策树是一种树状结构&#xff0c;通过做出一系列决策&#xff08;选择&#xff09;来对数据进行划分&#xff0c;这类似于针对一系列问题进行选择。决策树的决策过程就是从根节点开始&…

心理辅导|高校心理教育辅导系统|基于Springboot的高校心理教育辅导系统设计与实现(源码+数据库+文档)

高校心理教育辅导系统目录 目录 基于Springboot的高校心理教育辅导系统设计与实现 一、前言 二、系统功能设计 三、系统实现 1、学生功能模块的实现 &#xff08;1&#xff09;学生登录界面 &#xff08;2&#xff09;留言反馈界面 &#xff08;3&#xff09;试卷列表界…

Java实现实现自动化pdf打水印小项目 使用技术pdfbox、Documents4j

文章目录 前言源码获取一、需求说明二、 调研pdf处理工具word处理工具 三、技术栈选择四、功能实现实现效果详细功能介绍详细代码实现项目目录WordUtilsMain类实现部分&#xff1a;第一部分Main类实现部分&#xff1a;第二部分Main类实现部分&#xff1a;第三部分 资料获取 前言…

win7自带截图工具保存失效解决办法

今日发现一台远航技术的win7中自带的截图工具使用时正常&#xff0c;保存图片时没有弹出保存位置的对话窗口&#xff0c;无法正常保存图片。解决方案如下&#xff1a; 1、进入注册表编辑器。开始-搜索程序和文件-输入 regedit 按下回车键&#xff0c;打开注册表&#xff1b; 2、…

DS Wannabe之5-AM Project: DS 30day int prep day18

Q1. What is Levenshtein Algorithm? Levenshtein算法&#xff0c;也称为编辑距离算法&#xff0c;是一种量化两个字符串之间差异的方法。它通过计算将一个字符串转换成另一个字符串所需的最少单字符编辑操作次数来实现。这些编辑操作包括插入、删除和替换字符。Levenshtein距…

【知识图谱--第三讲知识图谱的存储与查询】

知识图谱的存储与查询 基于关系型数据库的知识图谱存储基于原生图数据库的知识图谱存储原生图数据库实现原理浅析 基于关系型数据库的知识图谱存储 基于原生图数据库的知识图谱存储 原生图数据库实现原理浅析

黑群晖一键修复:root、AME、DTS、转码、CPU型号等

食用方法&#xff1a;SSH连接群晖使用临时root权限执行 AME3.x激活补丁 只适用于x86_64的&#xff1a;DSM7.x Advanced Media Extensions (AME)版本3.0.1-2004、3.1.0-3005 激活过程需要下载官方的解码包&#xff0c;过程较慢&#xff0c;耐心等待。。。 DSM7.1和7.2的AME版…

CMake进行C/C++与汇编混合编程

1. 前提 这篇文章记录一下怎么用CMake进行项目管理, 并用C/C和汇编进行混合编程, 为了使用这项技术, 必须在VS的环境中安装好cmake组件 由于大部分人不会使用C/C与汇编进行混合编程的情况。所以这篇文章并不适用于绝大部分人不会对其中具体细节进行过多叙述。只是做一些简单的…

静态时序分析:SDC约束命令set_clock_transition详解

相关阅读 静态时序分析https://blog.csdn.net/weixin_45791458/category_12567571.html?spm1001.2014.3001.5482 在静态时序分析&#xff1a;SDC约束命令create_clock详解一文的最后&#xff0c;我们谈到了针对理想(ideal)时钟&#xff0c;可以使用set_clock_transition命令直…

数据发送程序

#include<reg51.h> //包含单片机寄存器的头文件 unsigned char code Tab[ ]{0xFE,0xFD,0xFB,0xF7,0xEF,0xDF,0xBF,0x7F}; //流水灯控制码&#xff0c;该数组被定义为全局变量 /***************************************************** 函数功能&#xff1a;向PC发…

wordpress外贸成品网站模板

首页大图slider轮播&#xff0c;橙色风格的wordpress外贸网站模板 https://www.zhanyes.com/waimao/6250.html 蓝色经典风格的wordpress外贸建站模板 https://www.zhanyes.com/waimao/6263.html