直接上代码
package com.paasit.pai.core.utils;
import org.apache.commons.lang.StringUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @description: 创建csv文件写入数据,并返回文件
* @Author: San Zhang
* @Date: 2023-03-02 13:31
*/
public class OSSCSVUtils {
/**
* 功能说明:获取UTF-8编码文本文件开头的BOM签名。
* BOM(Byte Order Mark),是UTF编码方案里用于标识编码的标准标记。例:接收者收到以EF BB BF开头的字节流,就知道是UTF-8编码。
*
* @return UTF-8编码文本文件开头的BOM签名
*/
public static String getBOM() {
byte b[] = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
return new String(b);
}
/**
* 生成CVS文件
*
* @param exportData 源数据List
* @param map csv文件的列表头map
* @param outPutPath 文件路径
* @return
*/
@SuppressWarnings("rawtypes")
public static File createCSVFile(List exportData, LinkedHashMap map, String outPutPath) {
File csvFile = null;
BufferedWriter csvFileOutputStream = null;
try {
File file = new File(outPutPath);
if (!file.exists()) {
file.mkdirs();
}
//定义文件名格式并创建
csvFile = new File(outPutPath);
file.createNewFile();
// UTF-8使正确读取分隔符","
//如果生产文件乱码,windows下用gbk,linux用UTF-8
csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
csvFile), "UTF-8"), 1024);
//写入前段字节流,防止乱码
csvFileOutputStream.write(getBOM());
// 写入文件头部
for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext(); ) {
java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
csvFileOutputStream.write((String) propertyEntry.getValue() != null ? (String) propertyEntry.getValue() : "");
if (propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
}
csvFileOutputStream.newLine();
// 写入文件内容
for (Iterator iterator = exportData.iterator(); iterator.hasNext(); ) {
Object row = (Object) iterator.next();
for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator
.hasNext(); ) {
java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
.next();
String str = row != null ? ((String) ((Map) row).get(propertyEntry.getKey())) : "";
if (StringUtils.isEmpty(str)) {
str = "";
} else {
// 处理特殊字符防止生成的文件数据错位
str = str.replaceAll("\"", "\"\"");
str = str.replaceAll("”", "\"\"");
str = str.replaceAll("\n", "\\\\n");
str = str.replaceAll("\r", "\\\\r");
if (str.indexOf(",") >= 0) {
str = "\"" + str + "\"";
} else if (str.indexOf(",") >= 0) {
str = "\"" + str + "\"";
}
}
csvFileOutputStream.write(str);
if (propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
}
if (iterator.hasNext()) {
csvFileOutputStream.newLine();
}
}
csvFileOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
csvFileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return csvFile;
}
public static void exportFile(HttpServletResponse response, String csvFilePath, String fileName) throws IOException {
response.setContentType("application/csv;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" +
URLEncoder.encode(fileName, "UTF-8"));
InputStream in = null;
try {
in = new FileInputStream(csvFilePath);
int len = 0;
byte[] buffer = new byte[1024];
response.setCharacterEncoding("UTF-8");
ServletOutputStream servletOutputStream = response.getOutputStream();
while ((len = in.read(buffer)) > 0) {
servletOutputStream.write(new byte[]{-17, -69, -65});
servletOutputStream.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
System.out.println(e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
public static void deleteFiles(String filePath) {
File file = new File(filePath);
if (file.exists()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
files[i].delete();
}
}
}
}
public static void deleteFile(String filePath, String fileName) {
File file = new File(filePath);
if (file.exists()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile() &&
files[i].getName().equals(fileName)) {
files[i].delete();
return;
}
}
}
}
}