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:
view:
suffix: .html
static-path-pattern: /**
<!DOCTYPE html>
<html lang="zh-cn">
<meta charset="UTF-8">
<title>测试上传demo</title>
</head>
<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
)
ThinkPHP6.0 修改器
修改器和获取器相反,修改器的主要作用是对模型设置的数据对象值进行处理。修改器方法的命名规范为:setFieldNameAttr修改器的使用场景和读取器类似:时间日期字段的转换写入;集合或枚举类型的写入
追女生时,如何做到不“怂”?(简单有效)
很多兄弟追女生,并不是败在了技巧上,而是心态上,这篇文章就是要告诉兄弟们,如何做到不“怂”,抱得美人归。很多兄弟在看过把妹技巧的文章后,还是反馈说碰到妹子不敢上,甚至在网上聊天时,都不敢表达自己的想法
php技术提升心得与方法
现在的PHP市场虽然充斥了大量的的PHP开发人员,但这些人当中真正能称得上高手的却寥寥无几。很多公司虽然招聘了一些PHP开发人员,但是由于技术水平不高,导致公司的项目一直堆积。这不仅另公司无奈也让已经入职的PHP开发人员着急,他们也想要在PHP领域更近一步,但却苦于找不到提高自己的方法,下面我们的鸥仔收集了一些PHP大神的一些工作方式、习惯,让大家看看PHP大神们是如何工作,也希望这些方法能帮助到那些想要在PHP领域更近一步的人。
shiro ajax返回登录成功
shiro默认在我们登录成功后会重定向到用户首页,有些时候,登录是使用ajax完成,登录成功后,会返回给我们登录成功的页面,尽管在ajax中页面不跳转我们可以手动跳转,但是还是有些不爽希望能返回jso
站点信息
-
建站时间
:2019-10-24
-
网站程序
:Thinkphp6 Layui
-
文章统计
:
247
篇文章
-
标签管理
:
标签云
-
统计数据
:
cnzz统计
-
微信公众号
:扫描二维码,关注我们
-