java导出cvs

public boolean exportDataToCSV(List dataList,
			LinkedHashMap<String, String> showTitle, String fileName,
			HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		boolean flag = false;
		if (response != null && request != null) {
			//获取浏览器类型
			final String userAgent = request.getHeader("USER-AGENT");
			// 输出流
			OutputStream out = null;

			// 待导出的数据
			StringBuffer exportDate = new StringBuffer();

			if (fileName == null) {
				fileName = "";
			}

			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
			fileName = fileName + formatter.format(curDate) + ".csv";

			if (userAgent.contains("MSIE")) {// IE浏览器
				fileName = URLEncoder.encode(fileName, "UTF8");
			} else if (userAgent.contains("Mozilla")) {// google,火狐浏览器
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} else {
				fileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
			}
			// 提示框设置
			response.reset(); // reset the response
			// response.setCharacterEncoding("UTF-8");
			 response.setContentType("application/octet-stream");
			response.setHeader("content-disposition", "attachment; filename=\""
					+ fileName + "\"");
			try {
				// 获得显示字段(实体属性)
				List<String> fields = new ArrayList<String>();
				// 表头(实体中文名称)
				if (showTitle != null && showTitle.size() > 0) {
					StringBuffer tableHead = new StringBuffer();
					for (Map.Entry<String, String> entry : showTitle.entrySet()) {
						tableHead.append(entry.getValue()).append(",");
						fields.add(entry.getKey());
					}
					// 添加表头
					exportDate.append(tableHead);
					exportDate.append("\n");
				}
				// 列表数据
				if (dataList != null && dataList.size() > 0) {
					Object obj = dataList.get(0);
					// 获得实体类的set/get方法
					Method methods[] = obj.getClass().getDeclaredMethods();
					// 将显示字段的get方法存入集合
					List<Method> invokeMethods = new ArrayList<Method>();
					for (int j = 0; j < fields.size(); j++) {
						for (int i = 0; i < methods.length; i++) {
							String methodName = methods[i].getName();
							String tmpMethodName = methodName.substring(3,
									methodName.length());
							if (fields.get(j).toString().trim().toUpperCase()
									.equals(tmpMethodName.toUpperCase())
									&& methodName.indexOf("set") != 0
									&& methodName.indexOf("get") == 0) {
								invokeMethods.add(methods[i]);
							}
						}
					}
					// 获取数据
					for (int i = 0; i < dataList.size(); i++) {
						obj = dataList.get(i);
						for (int j = 0; j < invokeMethods.size(); j++) {
							Method method = invokeMethods.get(j);
							Object tmpObj = method.invoke(obj);
							if (tmpObj == null) {
								tmpObj = "";
							}
							exportDate.append(tmpObj.toString());
							exportDate.append(",");
						}
						exportDate.append("\n");
					}
				}

				// System.out.println("============" + exportDate.toString());
				out = response.getOutputStream();
				byte[] bytes = exportDate.toString().getBytes("GBK");
				out.write(bytes);
				out.flush();
				// 关闭输出流
				if (out != null) {
					exportDate.delete(0, exportDate.length());
				}
				flag = true;
				log.info("文件导出完毕!");
			} catch (Exception e) {
				log.error(e);
				e.printStackTrace();
				log.error("导出数据时出现异常");
			} finally {
				if (out != null) {
					try {
						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}else{
			new NullPointerException("HttpServletRequest Or HttpServletResponse Is Null !");
		}
		return flag;
	}


//调用
@RequestMapping(value = "/exportDealerManager")
	public void exportQueryData(HttpServletRequest request, HttpServletResponse response, FlDealer flDealer) throws Exception {
		String fileName="名称";
		ExportDataUtil edu = new ExportDataUtil();
		List<FlDealer> dealerList = flDealerManagerService.getDealerList(flDealer);
		LinkedHashMap <String, String> showColumn = new LinkedHashMap <String, String>();
		//获取配置文件路径
		StringBuffer filePath = new StringBuffer();
		filePath.append(this.getClass().getResource("/"));
		filePath.append("exportClassConfig.xml");
		XMLOperUtil xmlUtil = new XMLOperUtil(filePath.substring(5).toString());
		List elements = xmlUtil.getElements("/Classes/DealerManagerDownload/property", false);
		//获取需要导出的字段
		for(int i= 0; i<elements.size();i++){
			Element el = (Element) elements.get(i);
			showColumn.put(el.attributeValue("ename"),el.attributeValue("cname"));
		}
		edu.exportDataToCSV(dealerList, showColumn, fileName, request, response);
	}

  

  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。