pom
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.1.2</version>
</dependency>
实体
package com.example.csvdemo.bean;
import lombok.Data;
/* *
* @program: csvdemo
* @description
* @author: swq
* @create: 2021-04-15 21:17
**/
@Data
public class CsvEntity {
private String name;
private String type;
}
package com.example.csvdemo.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.*;
import cn.hutool.core.util.CharsetUtil;
import com.example.csvdemo.bean.CsvEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/* *
* @program: csvdemo
* @description
* @author: swq
* @create: 2021-04-15 21:20
**/
@RestController
public class CsvController {
@GetMapping("/getCsv")
public void getCsv(HttpServletResponse response, HttpServletRequest request) {
// 模拟数据
List<CsvEntity> csvEntities = new ArrayList<>();
for (int i = 0; i < 5; i++) {
CsvEntity csvEntity = new CsvEntity();
csvEntity.setName("数据集" + i);
csvEntity.setType("类型" + i);
csvEntities.add(csvEntity);
}
// 组装数据
List<String[]> writeLine = new ArrayList<>();
for (CsvEntity csvEntity : csvEntities) {
String[] strings = new String[2];
strings[0] = csvEntity.getName();
strings[1] = csvEntity.getType();
writeLine.add(strings);
}
// 读数据
read();
// 写数据
write(response, writeLine);
}
/* *
* 输出 csv
* @param response
* @param writeLine
*/
private void write(HttpServletResponse response, List<String[]> writeLine) {
CsvWriter writer = null;
try {
writer = CsvUtil.getWriter("C:\\Users\\perfe\\Desktop\\数据集.csv", CharsetUtil.CHARSET_GBK);
writer.write(writeLine);
response.setContentType("application/csv;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("数据集.csv", "UTF-8"));
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (writer != null) {
writer.close();
}
}
}
/* *
* 读取数据封装到实体
*/
private void read() {
CsvReader reader = CsvUtil.getReader();
//从文件中读取CSV数据
CsvData data = reader.read(FileUtil.file("C:\\Users\\perfe\\Desktop\\list.csv"), CharsetUtil.CHARSET_GBK);
List<CsvRow> rows = data.getRows();
for (CsvRow row : rows) {
List<String> rawList = row.getRawList();
System.out.println(rawList);
}
List<CsvEntity> csvEntities = new ArrayList<>();
for (int i = 1; i < rows.size(); i++) {
CsvRow row = rows.get(i);
CsvEntity csvEntity = new CsvEntity();
List<String> rawList = row.getRawList();
csvEntity.setName(rawList.get(0));
csvEntity.setType(rawList.get(1));
csvEntities.add(csvEntity);
}
System.out.println(csvEntities);
}
}