Java 导出 csv 文件

//首先是一个servlet类
public class KpiExcel extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public KpiExcel() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("GBK");
		response.setContentType("application/x-xls");
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		response.addHeader("Content-Disposition",
				"attachment; filename=\"KpiDetail.csv\"");
		ServletOutputStream output = response.getOutputStream();

		ApplicationContext appCtx = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());
		NetKpiService netKpiService = (NetKpiService) appCtx
				.getBean("netKpiService");
		String cgId = request.getParameter("cgId");
		String kpiId = request.getParameter("kpiId");
		String time = request.getParameter("time");
		String type = request.getParameter("type");
		time = time.replace("-", "").replace(" ", "").replace(":00", "");
		Map queryMap = new HashMap();

		if (type.equalsIgnoreCase("group")) {
			queryMap.put("params", "customer_group_id=" + cgId + "&kpi_id="
					+ kpiId + "&h_id=" + time);
		} else if (type.equalsIgnoreCase("region")) {
			queryMap.put("params", "region_id=" + cgId + "&kpi_id=" + kpiId
					+ "&h_id=" + time);
		}
		queryMap.put("plugIn", "KPI_DETAIL");
		Map retMap = netKpiService.queryHasDownLoaded(queryMap);
		List codeList = netKpiService.queryKpiCodeByCode("KPI_DETAIL");
		if (retMap != null && retMap.size() > 0) {
			String resultTable = (String) retMap.get("result_table");
			String hiveSql = "select * from " + resultTable.toLowerCase();
			try {
				List kpiDetailList = HiveUtil.queryHive(hiveSql, HiveUtil
						.getHiveConn());
				CSVUtils.exportCsv(response, codeList, kpiDetailList);
				output.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void init() throws ServletException {
		// Put your code here
	}
}

//写数据进csv的工具类
public class CSVUtils {

	/**
	 * 
	 * @param response
	 * @param headers
	 *            文件头
	 * @param data
	 *            文件内容
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean exportCsv(HttpServletResponse response, List headers,
			List data) {
		boolean isSucess = false;

		String[] tagNames = new String[headers.size()];
		String[] columns = new String[headers.size()];

		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			osw = new OutputStreamWriter(os);
			bw = new BufferedWriter(osw);

			// 写入文件头部
			for (int i = 0; i < headers.size(); i++) {
				Map map = (Map) headers.get(i);
				tagNames[i] = (String) map.get("data_name");
				columns[i] = (String) map.get("data_code").toString().toLowerCase();
				bw.write("\"" + tagNames[i] + "\"");

				if (i + 1 != headers.size()) {
					bw.write(",");
				}
			}
			bw.newLine();

			// 写文件内容
			for (Iterator it = data.iterator(); it.hasNext();) {
				Map row = (Map) it.next();

				for (int i = 0; i < headers.size(); i++) {
					bw.write("\"" + row.get(columns[i]) + "\"");

					if (i + 1 != headers.size()) {
						bw.write(",");
					}
				}
				if (it.hasNext()) {
					bw.newLine();
				}
			}
			isSucess = true;
		} catch (Exception e) {
			isSucess = false;
		} finally {
			if (bw != null) {
				try {
					bw.close();
					bw = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (osw != null) {
				try {
					osw.close();
					osw = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (os != null) {
				try {
					os.close();
					os = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return isSucess;
	}
}


你可能感兴趣的:(java,csv)