您现在的位置是:首页 > java技术交流java技术交流
springboot apache.commons 上传和导出csv
上善若水2021-01-14 18:31:39【java技术交流】
21人已围观
简介csv是一种常用的表格数据,一般相比excel更加高效,在工作中大量使用,最近尝试了下使用commons-csv导出csv文件,我只是搬运工! 准备工作首先搭建一个简单springboot项目
csv是一种常用的表格数据,一般相比excel更加高效,在工作中大量使用,最近尝试了下使用commons-csv
导出csv文件,我只是搬运工!
准备工作
首先搭建一个简单springboot
项目
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.my</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.8</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
配置文件application.yml
spring:
mvc:
view:
suffix: .html
static-path-pattern: /**
在static里添加index.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>测试上传demo</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="提交">
</form>
<a href="/uploadCsv?name=中文.jpg">导出csv</a>
</body>
</html>
控制器代码
package com.my.demo.controller;
import com.my.demo.controller.util.CSVUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
@Controller
public class IndexController {
@GetMapping("/")
public String index() {
return "index";
}
@PostMapping("/")
@ResponseBody
public List index(@RequestParam(value = "file") MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
// InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "GBK");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
CSVParser parser = CSVFormat.DEFAULT.parse(bufferedReader);
List<List<String>> values = new ArrayList<>();
for (CSVRecord record : parser.getRecords()) {
List<String> value = new ArrayList<>();
for (int i = 0; i < record.size(); i++) {
value.add(record.get(i));
}
values.add(value);
}
return values;
}
@GetMapping("/uploadCsv")
public String uploadCsv(HttpServletResponse response) throws IOException {
String[] head ={"头1","头1","头3"};
List<String[]> values =new ArrayList<>();
for (int i=0;i<10;i++){
values.add(new String[]{"php最好的语言"+i, "java天下第一"+i, "python我年轻我骄傲"+i});
}
String fileName = "temp";
File file = CSVUtils.makeTempCSV(fileName, head, values);
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName +".csv");
CSVUtils.downloadFile(response, file);
return null;
}
}
工具类
产考:https://blog.csdn.net/u013620635/article/details/96877700
package com.my.demo.controller.util;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: Denebola
* @Date: 2019/7/18-16:48
* @Description: CSV工具类
**/
public class CSVUtils {
private static Logger logger = LoggerFactory.getLogger(CSVUtils.class);
//行尾分隔符定义
private final static String NEW_LINE_SEPARATOR = "\n";
//上传文件的存储位置
private final static String PATH = "E:/blog/";
/**
* @return File
* @Description 创建CSV文件
* @Param fileName 文件名,head 表头,values 表体
**/
public static File makeTempCSV(String fileName, String[] head, List<String[]> values) throws IOException {
// 创建文件
File file = File.createTempFile(fileName, ".csv", new File(PATH));
CSVFormat formator = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
BufferedWriter bufferedWriter =
new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
CSVPrinter printer = new CSVPrinter(bufferedWriter, formator);
// 写入表头
printer.printRecord(head);
// 写入内容
for (String[] value : values) {
printer.printRecord(value);
}
printer.close();
bufferedWriter.close();
return file;
}
/**
* @return boolean
* @Description 下载文件
* @Param response,file
**/
public static boolean downloadFile(HttpServletResponse response, File file) {
FileInputStream fileInputStream = null;
BufferedInputStream bufferedInputStream = null;
OutputStream os = null;
try {
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
os = response.getOutputStream();
//MS产本头部需要插入BOM
//如果不写入这几个字节,会导致用Excel打开时,中文显示乱码
os.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
byte[] buffer = new byte[1024];
int i = bufferedInputStream.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bufferedInputStream.read(buffer);
}
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
if (os != null) {
try {
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedInputStream != null) {
try {
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
file.delete();
}
return false;
}
/**
* @return File
* @Description 上传文件
* @Param multipartFile
**/
public static File uploadFile(MultipartFile multipartFile) {
String path = PATH + multipartFile.getOriginalFilename();
try {
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
multipartFile.transferTo(file);
logger.info("上传文件成功,文件名===>" + multipartFile.getOriginalFilename() + ", 路径===>" + file.getPath());
return file;
} catch (IOException e) {
logger.error("上传文件失败" + e.getMessage(), e);
return null;
}
}
/**
* @return List<List < String>>
* @Description 读取CSV文件的内容(不含表头)
* @Param filePath 文件存储路径,colNum 列数
**/
public static List<List<String>> readCSV(String filePath, int colNum) {
BufferedReader bufferedReader = null;
InputStreamReader inputStreamReader = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filePath);
inputStreamReader = new InputStreamReader(fileInputStream);
bufferedReader = new BufferedReader(inputStreamReader);
CSVParser parser = CSVFormat.DEFAULT.parse(bufferedReader);
// 表内容集合,外层List为行的集合,内层List为字段集合
List<List<String>> values = new ArrayList<>();
int rowIndex = 0;
for (CSVRecord record : parser.getRecords()) {
// 跳过表头
if (rowIndex == 0) {
rowIndex++;
continue;
}
// 每行的内容
List<String> value = new ArrayList<>(colNum + 1);
for (int i = 0; i < colNum; i++) {
value.add(record.get(i));
}
values.add(value);
rowIndex++;
}
return values;
} catch (IOException e) {
logger.error("解析CSV内容失败" + e.getMessage(), e);
} finally {
//关闭流
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
最后看看结果
下载
导出
很赞哦! (0)
相关文章
随机图文
哄女孩子开心的幽默笑话!!
1.黑猩猩不小心踩到了长臂猿拉的大便,长臂猿温柔细心地帮其擦洗干净后它们相爱了。别人问起他们是怎么走到一起的?黑猩猩感慨地说:猿粪!都是猿粪啊!2.我说:“你是猪。”你说:“我是猪才怪!”从此我就叫你猪才怪。终于有一天,你忍不住当着众人的面对我吼道:“我不是猪才怪!”3.明天你醒来,枕边躺着一只蚊子,身边有一封遗书,上书:我奋斗了一晚,也没能刺破你的脸,你的脸皮厚得让我无颜活在这世上!主啊抖音笑话段子撩人套路
1、从今日开端我茹素,由于你是我的菜 2、你晓得泰语 撒那嘿呦是甚么意义吗? 我爱你 我也是 3、我觉得你今日怎样这么怪啊? 那里怪了? 怪好看的!! 4、美男,跟你问一下,那条路怎样走? 哪条路? 通往你内心的路 5、你有舆图吗? 怎样了? 我在你的眼睛里迷路了 6、哎,给你看一个美男? 甚么?_? 拿镜子照向她 7、你能够帮我洗个工具吗? 洗甚么? (洗)喜好我 8、你会模拟啄木鸟吗 会啊 来,把我的脸当作树 9、女:小哥哥,小哥哥,给你个工具你要吗? 男:甚么呀爆笑喷饭的长篇笑话集锦
1.高中的时候,一次下课,同学们都抢着到外面买盒饭。一女生为了比别人先到,绕了个近道走,结果前面窨井盖没盖好,掉了下去!一会儿她撑着井沿往上爬,很是狼狈,一群初中小孩惊骇地从身边走过,她竟急中生智,一边爬一边说:哎!真难修啊……2.还是中学时,夏天裸睡被蚊子咬到DD,上课奇痒难忍,可总不能伸进去抓痒吧,我忍!痛不欲生!课间偷了同桌(女生)的一盒清凉油狂奔厕所,抹上之后才追悔莫及————那个刺激62个哄女孩开心的笑话,只为博你一笑!泡妞必备!
1.一天,牛给驴出了一个难题,问“蠢”字下面两只虫子哪只是公的,哪只是母的。驴绞尽脑汁,还是答不上来。牛骂道:真是头蠢驴,男左女右嘛!2.毕业后七年,总算接了个大工程,造一根三十米烟囱,工期两个月,造价三十万,不过要垫资。总算在去年年底搞完了。今天人家去验收,被人骂得要死,还没有钱拿。妈的!图纸看反了,人家是要挖一口井!3.一醉汉不慎从三楼掉下,引来路人围观,一警察过来:发生什么事?醉汉