您现在的位置是:首页 > java技术交流java技术交流
springboot apache.commons 上传和导出csv
上善若水2021-01-14 18:31:39【java技术交流】 5481人已围观
简介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;
}
}
最后看看结果
下载
导出
很赞哦! (2)
相关文章
随机图文
-
这些哭笑不得的冷笑话,你被哪个逗笑?
1.皮卡丘去找喷火龙借钱,喷火龙不借让他去找杰尼龟,然后杰尼龟说:不借,你是不是以为我只会说杰尼杰尼? 2.我对象说今年过年回家看我父母 象说:不了 3.阿基米德说:给我一个支点,我能用杠杆撬动整个地球! 投资机构:这个三倍杠杆拿去不谢。 第二天,阿基米德发现自己亏了2个地球! 4.“我以前也不懂事,后来被人打了一顿。” “就变懂事了?” “还是不懂事,但不敢嚣张了。” 5.下水 -
有哪些「能笑死人」的笑话?
1.在我上大学的时候,班里班花怀孕了,班花说孩子他爸是我们班的,辅导员找每个男生去办公室谈话,轮到我时,辅导员淡定的说:你回去吧,我相信你! 2.女同事产假回来第一天上班,我不记得她生孩子时我随礼没随礼,灵机一动,给她发了个红包,如果她收了就证明我没随礼,反之她不会收钱。 不一会,红包被收了,女同事回复说:谢谢哦,我替我家二宝先收下咯! 3.做事一向粗枝大叶的小芳在校内图书馆打工,顺便帮忙打扫 -
发几个笑话,差点没把人笑晕,专治不开心
1:我坐在沙发上,娃儿趴在我肩膀上闹腾。突然她停下来说:“老爸,你后脑勺上有白头发了!”我无奈的笑了笑:“头发白是因为老爸每天要操心很多事,很辛苦。所以你要心疼老爸知道不?”小家伙想了想,从沙发上跳下来,心疼的搂住Summer(我家的萨摩耶):“唉,家里就你最辛苦了。全身都白了!” 2:以前惹媳妇儿生气后,我就模仿曾志伟、周星驰的声音哄她。楼主学过播音,虽不能说学的惟妙惟肖,却也能把她逗笑,矛盾 -
爆笑喷饭的长篇笑话集锦
1.高中的时候,一次下课,同学们都抢着到外面买盒饭。一女生为了比别人先到,绕了个近道走,结果前面窨井盖没盖好,掉了下去!一会儿她撑着井沿往上爬,很是狼狈,一群初中小孩惊骇地从身边走过,她竟急中生智,一边爬一边说:哎!真难修啊……2.还是中学时,夏天裸睡被蚊子咬到DD,上课奇痒难忍,可总不能伸进去抓痒吧,我忍!痛不欲生!课间偷了同桌(女生)的一盒清凉油狂奔厕所,抹上之后才追悔莫及————那个刺激