/**
* csv下载工具类
*/
public class CSVUtils {
/**
* CSV文件列分隔符
*/
private static final String CSV_COLUMN_SEPARATOR = ",";
/**
* CSV文件列分隔符
*/
private static final String CSV_RN = "\r\n";
/**
* 导出csv格式文件
* @param data 要导出的数据
* @param clazz 数据对象类型
* @param header 表头
* @param matchColNames 需要匹配的字段名
* @return
*/
public static StringBuffer formatCsvInfo(List<?> data, Class<?> clazz, String header, String matchColNames) {
if (null == data || null == header || null == matchColNames) {
return null;
}
StringBuffer content = new StringBuffer();
String[] headerArr = header.split(CSV_COLUMN_SEPARATOR);
String[] matchColNameArr = matchColNames.split(CSV_COLUMN_SEPARATOR);
// 输出列头
for (int i = 0; i < headerArr.length; i++) {
content.append(headerArr[i]);
content.append(CSV_COLUMN_SEPARATOR);
}
content.append(CSV_RN);
//组装数据
for (Object obj : data) {
try {
for (int i = 0; i < matchColNameArr.length; i++) {
String methodName = "get" + matchColNameArr[i].substring(0, 1).toUpperCase() + matchColNameArr[i].substring(1);
Object value = clazz.getDeclaredMethod(methodName).invoke(obj);
content.append(value);
content.append(CSV_COLUMN_SEPARATOR);
}
content.append(CSV_RN);
} catch (Exception ex) {
ex.printStackTrace();
}
}
return content;
}
/**
* 导出csv格式文件
*
* @param fileName
* @param content
* @param response
* @throws IOException
*/
public static void exportCsv(String fileName, String content, HttpServletResponse response) throws IOException {
// 设置文件后缀
String fn = fileName.concat(".csv");
// 设置响应
response.setCharacterEncoding("UTF-8");
response.setContentType("text/csv; charset=UTF-8");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=30");
response.setHeader("Content-Disposition", "attachment; filename=" + new String(fn.getBytes(), "UTF-8"));
// 写出响应
try(OutputStream os = response.getOutputStream()){
os.write(content.getBytes("GBK"));
os.flush();
}
}
}