@RequestMapping("/doExport")
public void doExport(Model model, @RequestParam(value = "single") String ids, HttpServletResponse response) {

logger.info("输入____方法名称:doExport,参数:ids: " + ids);

List<Map<String, Object>> dataList = null;
String displayColNames = null;
String matchColNames = null;
String fileName = null;
String content = null;

dataList = this.phoneCatentryMgrService.doExport(ids);

// 完成数据csv文件的封装
displayColNames = "手机商品编码,手机类型,运营商,购机送费虚拟编码,存费送机虚拟编码";
matchColNames = "PHONE_PARTNUM,PHONE_TYPE_NAME,TELECOM_OPR_NAME,GJSF_PARTNUM,CFSJ_PARTNUM";
fileName = "phone_info_";

content = CsvWriter.formatCsvData(dataList, displayColNames, matchColNames);

try {
CsvWriter.exportCsv(fileName, content, response);
} catch (IOException e) {
logException(logger, e);
}

}


[java] view plain copy
public class CsvWriter {

/** CSV文件列分隔符 */
private static final String CSV_COLUMN_SEPARATOR = ",";

/** CSV文件列分隔符 */
private static final String CSV_RN = "\r\n";

/**
*
* 将检索数据输出的对应的csv列中
* */
public static String formatCsvData(List<Map<String, Object>> data,
String displayColNames, String matchColNames) {

StringBuffer buf = new StringBuffer();

String[] displayColNamesArr = null;
String[] matchColNamesMapArr = null;

displayColNamesArr = displayColNames.split(",");
matchColNamesMapArr = matchColNames.split(",");

// 输出列头
for (int i = 0; i < displayColNamesArr.length; i++) {
buf.append(displayColNamesArr[i]).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);

if (null != data) {
// 输出数据
for (int i = 0; i < data.size(); i++) {

for (int j = 0; j < matchColNamesMapArr.length; j++) {
buf.append(data.get(i).get(matchColNamesMapArr[j])).append(
CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);
}
}
return buf.toString();
}
public static void exportCsv(String fileName, String content,
HttpServletResponse response) throws IOException {

// 设置文件后缀
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhh24mmss");
String fn = fileName.concat(sdf.format(new Date()).toString() + ".csv");

// 读取字符编码
String csvEncoding = PropertiesUtil.getProperty("CSV_ENCODING");

// 设置响应
response.setCharacterEncoding(csvEncoding);
response.setContentType("text/csv; charset=" + csvEncoding);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=30");
response.setHeader("Content-Disposition", "attachment; filename="
+ new String(fn.getBytes(), csvEncoding));

// 写出响应
OutputStream os = response.getOutputStream();
os.write(content.getBytes("GBK"));
os.flush();
os.close();
}

}

转http://blog.csdn.net/xieshengjun2009/article/details/12192079

posted on 2016-11-24 10:28  Salansun  阅读(529)  评论(0编辑  收藏  举报