/**
* CSV文件列分隔符
*/
private static final String CSV_COLUMN_SEPARATOR = ",";
/**
* CSV文件行分隔符
*/
private static final String CSV_ROW_SEPARATOR = "\r\n";
/**
* @param dataList 集合数据
* @param titles 表头部数据
* @param keys 表内容的键值
* @param os 输出流
*/
public static void doExport(List<Map<String, Object>> dataList, List<String> titles, List<String> keys, OutputStream os) throws Exception {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd");
// 保证线程安全
StringBuffer buf = new StringBuffer();
// 组装表头
for (String title : titles) {
buf.append(title).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_ROW_SEPARATOR);
// 组装数据
if (CollectionUtils.isNotEmpty(dataList)) {
for (Map<String, Object> data : dataList) {
Set<String> strings = data.keySet();
for (String key : strings) {
Object o = data.get(key);
if (o.getClass().equals(Date.class)){
o = simpleDateFormat.format(o);
buf.append("\t"+o+"\t").append(CSV_COLUMN_SEPARATOR);
continue;
}
buf.append(o).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_ROW_SEPARATOR);
}
}
// 写出响应
os.write(buf.toString().getBytes("GBK"));
os.flush();
}
/**
* 设置Header
*
* @param fileName
* @param response
* @throws UnsupportedEncodingException
*/
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.setCharacterEncoding(utf);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=30");
try {
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
csv文件导出
最新推荐文章于 2024-07-25 13:40:37 发布