maven依赖
<!--csv依赖 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.7</version>
</dependency>
<!--上传工具依赖 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
导出工具类 CSVUtils
package com.ruoyi.common.core.utils.poi;
import com.ruoyi.common.core.utils.file.FileUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @ClassName CSVUtils * @Description TODO
* @Author lgn
* @Date 16:18 2022/9/13
* @Version 1.0
**/
public class CSVUtils {
/**
* CSV文件列分隔符
*/
private static final String CSV_COLUMN_SEPARATOR = ",";
/**
* CSV文件列分隔符
*/
private static final String CSV_RN = "\r\n";
/**
*
* @param dataList 集合数据
* @param colNames 表头部数据
* @param mapKey 查找的对应数据
* @param os 返回结果
*/
public static void doExport(List<Map<String, Object>> dataList, String colNames, String mapKey, OutputStream os) throws IOException {
try {
StringBuffer buf = new StringBuffer();
String[] colNamesArr = null;
String[] mapKeyArr = null;
colNamesArr = colNames.split(",");
mapKeyArr = mapKey.split(",");
// 完成数据csv文件的封装
// 输出列头
for (String aColNamesArr : colNamesArr) {
buf.append(aColNamesArr).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);
if (null != dataList) { // 输出数据
for (Map<String, Object> aDataList : dataList) {
for (String aMapKeyArr : mapKeyArr) {
buf.append(aDataList.get(aMapKeyArr)).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);
}
}
// 写出响应
os.write(buf.toString().getBytes("GBK"));
os.flush();
} catch (Exception e) {
throw e;
} finally {
if (os != null) {
try {
os.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
/**
* setHeader
*/
public static void responseSetProperties(HttpServletRequest request, String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
// 设置文件后缀
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fn = fileName + sdf.format(new Date()) + ".csv";
// 读取字符编码
String utf = "UTF-8";
// 设置响应
response.setContentType("application/ms-txt.numberformat:@");
response.setCharacterEncoding(utf);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=30");
//response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
response.setHeader("Content-Disposition",
"attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fn));//重新生成的新文件的名字
}
}
导入工具类
package com.ruoyi.common.core.utils.poi;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName CsvImportUtil * @Description TODO
* @Author lgn
* @Date 17:09 2022/9/13
* @Version 1.0
**/
public class CsvImportUtil {
//上传文件的路径
private final static URL PATH = Thread.currentThread().getContextClassLoader().getResource("");
/**
* @return File 一般文件类型
* @Description 上传文件的文件类型
* @Param multipartFile
**/
public static File uploadFile(MultipartFile multipartFile) {
// 获 取上传 路径
String path = PATH.getPath() + multipartFile.getOriginalFilename();
try {
// 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例
File file = new File(path);
// 此抽象路径名表示的文件或目录是否存在
if (!file.getParentFile().exists()) {
// 创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录
file.getParentFile().mkdirs();
}
// 转换为一般file 文件
multipartFile.transferTo(file);
return file;
} catch (IOException e) {
e.printStackTrace();
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, "GBK");
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;
}
// 判断下角标是否越界
if (colNum > record.size()) {
// 返回空集合
return values;
}
// 每行的内容
List<String> value = new ArrayList<>();
for (int i = 0; i < colNum; i++) {
value.add(record.get(i));
}
values.add(value);
rowIndex++;
}
return values;
} catch (IOException e) {
e.printStackTrace();
} 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;
}
}
Controller
/**
* 导出资产管理列表"
*/
@ApiOperation(value = "导出资产管理列表", notes = "导出资产管理列表", httpMethod = "POST")
@Log(title = "导出资产管理列表", businessType = BusinessType.EXPORT)
@PostMapping("/exportAssetsManageList")
public void exportAssetsManageList(HttpServletResponse response, HttpServletRequest request, LgsAssetsManage lgsAssetsManage)
{
List<Map<String,Object>> list = lgsAssetsManagementService.getAssetsManageMapList(lgsAssetsManage);
if (list.size() == 0) {
AjaxResult ajax = AjaxResult.error(503,"无数据导出");
}
String sTitle = "owner,systemName,systemNumber,instrumentNum,terminalNum,completionTime,operationDays,updatedBy,updatedTime";
String fName = "AssetsManage_";
String mapKey = "owner,systemName,systemNumber,instrumentNum,terminalNum,completionTime,operationDays,updatedBy,updatedTime";
try (final OutputStream os = response.getOutputStream()) {
CSVUtils.responseSetProperties(request,fName, response);
CSVUtils.doExport(list, sTitle, mapKey, os);
} catch (Exception e) {
}
}
@ApiOperation(value = "导入资产管理", notes = "导入资产管理", httpMethod = "POST")
@Log(title = "导入资产管理", businessType = BusinessType.IMPORT)
@PostMapping(value ="csvImportAssetsManage", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void csvImportAssetsManage(@RequestPart("file") MultipartFile file)
{
// 使用CSV工具类,生成file文件
File csvFile = CsvImportUtil.uploadFile(file);
// 将文件内容解析,存入List容器,List<String>为每一行内容的集合,6为CSV文件每行的总列数
List<List<String>> lists = CsvImportUtil.readCSV(csvFile.getPath(), 6);
lists.stream().forEach(info -> {
// 处理业务逻辑代码
System.out.println("info:"+info);
});
}