文章目录
- 前言
- 一、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 {
@Autowired
private 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;
}
@Override
public 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 {
@Override
protected Object convert(String s) throws CsvDataTypeMismatchException, CsvConstraintViolationException {
if(s.equals("否")){
return '0';
}
if(s.equals("是")){
return '1';
}
return null;
}
@Override
public 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点这里