CSV文件
1、CSV文件是一种用逗号分隔数值的文本文件,可以直接用Excel打开,也可以用于导入其他系统。
2、导出的文件为csv格式,请双击用Excel打开后请另存为excel文件。
3、如果打开后乱码,请使用记事本打开CSV文件,“文件”->“另存为”,编码方式选择ANSI,保存完毕后,用EXCEL打开这个文件就不会出现乱码的情况。
Xls文件
Xls文件是标准的Excel文件,可以直接用Excel打开,无乱码现象。数据量较大时,导出速度会很慢
实现代码工具类(方法一):
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
/**
* 导出CSV文件工具类
*/
@Slf4j
public class ExportCsvUtil {
/**
* CSV文件列分隔符
*/
private static final String CSV_COLUMN_SEPARATOR = ",";
/**
* CSV文件行分隔符
*/
private static final String CSV_ROW_SEPARATOR = System.lineSeparator();
/**
* @param response 响应流
* @param fileName 文件名称
* @param titleColumn 标题列名称对象(如:name)
* @param titleName 标题列名称对象描述(如:张三)
* @param dataList 数据源
*/
public static void writeCSV(HttpServletResponse response, String fileName, String titleColumn[], String titleName[], List> dataList) {
OutputStream out = null;
try {
// 保证线程安全
StringBuffer buf = new StringBuffer();
out = response.getOutputStream();
String lastFileName = fileName + ".csv";
response.setContentType("application/msexcel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(lastFileName, "UTF-8"));
// 组装表头
for (String title : titleName) {
buf.append(title).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_ROW_SEPARATOR);
//组装行数据
for (int index = 0; index < dataList.size(); index++) {
Object obj = dataList.get(index);
Class clazz = obj.getClass();
for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
String title = titleColumn[columnIndex].trim();
if (!"".equals(title)) {
// 获取返回类型
String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length()); // 使其首字母大写;
String methodName = "get" + UTitle;
Method method = clazz.getDeclaredMethod(methodName);
String returnType = method.getReturnType().getName();
Object object = method.invoke(obj);
//获取到数据
String data = method.invoke(obj) == null ? "" : object.toString();
//组装数据
buf.append(data).append(CSV_COLUMN_SEPARATOR);
}
}
buf.append(CSV_ROW_SEPARATOR);
}
//输出
out.write(buf.toString().getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
log.error("导出写Csv异常");
}
}
}
}
}
方法二:
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
/**
* 导出CSV文件工具类
*/
@Slf4j
public class ExportCsvUtil {
/**
* 需要引入的jar包
*
* org.apache.commons
* commons-csv
* 1.6
*
*/
/**
* @param response 响应流
* @param fileName 文件名称
* @param titleColumn 标题列名称对象(如:name)
* @param titleName 标题列名称对象描述(如:张三)
* @param dataList 数据源
*/
public static void writeCSV1(HttpServletResponse response, String fileName, String titleColumn[], String titleName[], List> dataList) {
OutputStream out = null;
try {
out = response.getOutputStream();
String lastFileName = fileName + ".csv";
response.setContentType("application/msexcel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(lastFileName, "UTF-8"));
OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
//追加BOM标识(bom这个可自行百度了解)
osw.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));
//写入标题
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(titleName);
CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);
//组装行数据
for (int index = 0; index < dataList.size(); index++) {
Object obj = dataList.get(index);
Class clazz = obj.getClass();
String str[] = new String[titleColumn.length];
for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
String title = titleColumn[columnIndex].trim();
if (!"".equals(title)) {
// 获取返回类型
String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1); // 使其首字母大写;
String methodName = "get" + UTitle;
Method method = clazz.getDeclaredMethod(methodName);
String returnType = method.getReturnType().getName();
Object object = method.invoke(obj);
//获取到数据
String data = method.invoke(obj) == null ? "" : object.toString();
if (Date.class.getName().equals(returnType)) {
str[columnIndex]=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(object);
} else {
//组装数据
str[columnIndex]=data;
}
}
}
//打印一行
csvPrinter.printRecord(str);
}
csvPrinter.flush();
csvPrinter.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
log.error("导出Csv异常");
}
}
}
}
}
测试对象:
@ApiModel("数据返回类")
@Data
public class NilometerDataResp {
@ApiModelProperty(value = "水位(单位:cm)")
private String waterLevel;
@ApiModelProperty(value = "水位(单位:cm)")
private Integer waterTemp;
}
@GetMapping("/export")
@ApiOperation(value = "数据导出接口", notes = "数据导出接口")
public void exportMyAlarmOfApp(HttpServletResponse response) {
List exportList = new ArrayList<>();
for (int i=1; i<6;i++){
NilometerDataResp model = new NilometerDataResp();
model.setWaterLevels("水位"+i);
model.setWaterTemp(23+i);
exportList.add(model);
}
DateFormat df1 = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = "Test" + df1.format(new Date());
String titleColumn[] = new String[]{"waterLevel", "waterTemp"};
String titleName[] = new String[]{"水位", "水温"};
//执行导出
ExportCsvUtil.writeCSV(response, fileName, titleColumn, titleName, exportList);
}