工具类
package com.ybkj.mg.util;
import org.apache.commons.collections.CollectionUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class CsvExportUtil {
private static final String CSV_COLUMN_SEPARATOR = ",";
private static final String CSV_ROW_SEPARATOR = System.lineSeparator();
public static void doExport(List<Map<String, Object>> dataList, String titles, String keys, OutputStream os) throws Exception {
StringBuffer buf = new StringBuffer();
String[] titleArr = null;
String[] keyArr = null;
titleArr = titles.split(",");
keyArr = keys.split(",");
for (String title : titleArr) {
buf.append(title).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_ROW_SEPARATOR);
if (CollectionUtils.isNotEmpty(dataList)) {
for (Map<String, Object> data : dataList) {
for (String key : keyArr) {
buf.append(data.get(key)).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_ROW_SEPARATOR);
}
}
os.write(buf.toString().getBytes("GBK"));
os.flush();
}
public static void responseSetProperties(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));
}
}
业务层调用
List<SubLogDetailBean> list = chargLogService.findSubAllORCondition(cdzChargLogQuery);
List<Map<String, Object>> datas = new ArrayList<>();
String titles = "序号,流水号";
String keys = "num,logId";
Map<String,Object> map = null;
int i = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for(SubLogDetailBean data : list){
map = new HashMap<>();
map.put("num",i++);
map.put("logId",data.getLogid() == null ? "" : data.getLogid().toString());
map.put("subId",data.getSubid() == null ? "" : data.getSubid().toString());
datas.add(map);
}
String fName = "记录";
OutputStream os = response.getOutputStream();
CsvExportUtil.responseSetProperties(fName,response);
CsvExportUtil.doExport(datas,titles,keys,os);
os.close();