java实现CSV文件输出 收藏 在很多时候我们都需要将一些数据集合以某种文件格式输出,其中CSV文件输出是一种比较常用的方式. 下面是一个简单的实现CSV文件输出的代码,与大家共享.
public static boolean createCsv(HttpServletResponse Response, QueryData qryData, String[][] columnName) throws Exception { String data = ""; SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmm"); Date today = new Date(); String dateToday = dataFormat.format(today); if (qryData.size() == 0 || columnName.length == 0) return false;
data += "编号,"; for (int i = 0; i < columnName.length; i++) { data += columnName[i][1] + ","; } data += "\n"; for (int i = 0; i < qryData.size(); i++) { data += String.valueOf(i + 1) + ","; for (int j = 0; j < columnName.length; j++) { data += qryData.getRow(i).get(columnName[j][0]) + ","; } data += "\n"; } StringBuilder str = new StringBuilder(); str.append(data); Response.setHeader("Content-Disposition", "attachment; filename=\"" + dateToday + ".csv" + "\""); Response.setCharacterEncoding("shift-jis"); Response.setContentType("text/plain;charset=shift-jis"); PrintWriter out = Response.getWriter(); out.write(str.toString()); out.flush(); out.close(); return true; }
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/John_zhaohui/archive/2007/06/16/1654193.aspx
|