导出(下载)数据库查询的数据生成csv文件

jr项目总结 专栏收录该内容
2 篇文章 0 订阅

	@SuppressWarnings({ "unchecked" })
	public String downLoadCsvFile(){
		System.out.println("下载csv提现对账文件");
		
		HttpServletResponse response1 = ServletActionContext.getResponse();
		
		System.out.println("response1:"+response1);
		//从表中查询出数据
		String sql = "select t.* from TB_XXX t ";
		if(searchTime==null){//如果查询时间为空则默认查询昨天的
			//赋默认值
			System.out.println("默认查询昨天的");
			Calendar cal= Calendar.getInstance();
			cal.add(Calendar.DATE, -1);
			String yesterday = new SimpleDateFormat( "yyyy-MM-dd").format(cal.getTime());
			searchTime=yesterday;
		}
		log.info("searchTime为:"+searchTime);
		log.info("accountStatusState为:"+accountStatusState);
		sql+="where t.settle_date=to_char(to_date('"+searchTime+"','YYYY-MM-DD'),'YYYYMMDD') ";
		if(accountStatusState!=null&&!("").equals(accountStatusState)&&accountStatusState!=3){
			sql+="and t.diff_flag="+accountStatusState;
		}
//		else{
//			accountStatusState = 3;
//			sql+="and t.diff_flag="+accountStatusState;
//		}
//		
		log.info("查询语句为:"+sql);
//		pageBean=accountCheckService.findBySql(sql, pageBean);
		/**
		 * 根据原生sql查询
		 */
		List<AccountCheck> datalist = accountCheckService.findBySqlToClass(sql);
//		List<AccountCheck> datalist = pageBean.getDataList();
		System.out.println("datalist="+datalist);
//		List<String> datalist2 = Arrays.asList(datalist.toString());
//		List refundList = null;
		//下载后,跳转到cashMoneyList.jsp
		System.out.println("真假:"+datalist.toString().equals("[]"));
		if(datalist!=null&&!datalist.toString().equals("")&&!datalist.toString().equals("[]")){
			List exportData = new ArrayList();
			LinkedHashMap datamMap = null;
//			HashMap map = null;
			for(int i=0;i<datalist.size();i++){
				datamMap = new LinkedHashMap();
				datamMap.put("1", datalist.get(i).getOrder_num()!=null?datalist.get(i).getOrder_num():"");
				datamMap.put("2", datalist.get(i).getPay_num()!=null?datalist.get(i).getPay_num():"");
				datamMap.put("3", datalist.get(i).getOrder_time()!=null?datalist.get(i).getOrder_time():"");
				datamMap.put("4", datalist.get(i).getSettle_date()!=null?datalist.get(i).getSettle_date():"");
				datamMap.put("5", datalist.get(i).getOrder_money()!=null?datalist.get(i).getOrder_money():"");
				datamMap.put("6", datalist.get(i).getPay_money()!=null?datalist.get(i).getPay_money():"");
				datamMap.put("7", datalist.get(i).getPay_rate()!=null?datalist.get(i).getPay_rate():"");
				if(datalist.get(i).getYt_status()==null){
					yt_status="";
				}else if(datalist.get(i).getYt_status().equals("0")){
					yt_status = "成功";
				}else if(datalist.get(i).getYt_status().equals("5")){
					yt_status = "退款";
				}else{
					yt_status = "";
				}
				datamMap.put("8", yt_status);
				if(datalist.get(i).getDiff_flag()==null){
					diff_flag="";
				}else if(datalist.get(i).getDiff_flag().equals("1")){
					diff_flag = "银无我有";
				}else if(datalist.get(i).getDiff_flag().equals("2")){
					diff_flag = "银有我无";
				}else if(datalist.get(i).getDiff_flag().equals("0")){
					diff_flag = "平账";
				}else{
					diff_flag = "";
				}
				datamMap.put("9", diff_flag);
				datamMap.put("10", datalist.get(i).getRefund_date()!=null?datalist.get(i).getRefund_date():"");
				if(datalist.get(i).getPay_type()==null){
					pay_type="";
				}else if(datalist.get(i).getPay_type().equals("1")){
					pay_type = "银行卡";
				}else if(datalist.get(i).getPay_type().equals("2")){
					pay_type = "钱包";
				}else{
					pay_type = "";
				}
				datamMap.put("11", pay_type);
				if(datalist.get(i).getUser_type()==null){
					user_type = "";
				}else if(datalist.get(i).getUser_type()==1){
					user_type = "发行商";
				}else if(datalist.get(i).getUser_type()==2){
					user_type = "普通用户";
				}else{
					user_type = "";
				}
				datamMap.put("12", user_type);
				exportData.add(datamMap);
			}
			System.out.println("输出到对账表的数据为exportData:"+exportData);
			
			//定义导出的文件名
			String name = "XX支付对账文件_清算日期_"+searchTime+"_";
			try {
				fileName = new String(name.getBytes("utf-8"), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			LinkedHashMap map2 = new LinkedHashMap(); 
			map2.put("1", "订单号"); 
			map2.put("2", "支付流水号"); 
			map2.put("3", "订单时间"); 
			map2.put("4", "清算日期"); 
			map2.put("5", "订单金额"); 
			map2.put("6", "支付金额"); 
			map2.put("7", "手续费"); 
			map2.put("8", "XX交易状态"); // 0 成功 5 退款
			map2.put("9", "对账结果"); // 1 表示X无我有,2 表示X有我无,0 表示平帐
			map2.put("10", "退款时间"); 
			map2.put("11", "支付方式"); //1 银行卡 2 钱包
			map2.put("12", "用户类型"); //1 银行卡 2 钱包
//			String filePath= "c:\\Users\\Administrator\\Desktop\\";
//			String filePath="/home/lljrweb/filepath";
			String osName = System.getProperty("os.name");
			if (osName.contains("Linux")){
				filePath=Content.csvfilepath;
			}else{
				filePath="D:\\apache-tomcat-7.0.53\\csvfilepath";
			}
			File csvfile = CSVUtil.createCSVFile(exportData, map2, filePath, fileName);//生成CSV文件 
			try {//将生成的csv文件转换为流
				fileInputStream = new FileInputStream(csvfile);
				System.out.println("将文件转换成流");
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
			fileName = csvfile.getName(); //文件下载名称名
			log.info("fileName:"+fileName);
//			String fileName2 = fileName.substring(0,20)+".csv";
//			System.out.println("新的fileName2:"+fileName2);
//			try {
//				log.info("619");
//				CSVUtil.exportFile(response1, filePath + fileName, fileName);
//				msg = "6";
//			} catch (IOException e) {
//				msg = "7";
//				e.printStackTrace();
//			}//下载生成的CSV文件,重定向到列表页面
		}else{//返回数据为空
			log.info("查询的数据datalist为空");
			msg = "7001";//提示改天数据为空
			return "toList";
			
		}
		System.out.println("返回success");
		return "success";
	}

下载成csv文件工具类

package com.lljr.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

/**
 * 对账管理下载对账文件,生成.csv文件方法
 * @author gxy
 * @date 2016-3-4下午02:11:10
 */
/**
 * 文件操作
 */
public class CSVUtil {
	/**
	 * 生成位csv文件
	 * @param exportData
	 * 			源数据List
	 * @param map
	 * 			csv文件的列表头map
	 * @param outPutPath
	 * 			文件路径
	 * @param fileName
	 * 			文件名称
	 * @return
	 * @date 2016-3-4下午02:49:33
	 */
	@SuppressWarnings("unchecked")
	public static File createCSVFile(List exportData, LinkedHashMap map, String outPutPath,String fileName){
		File csvFile = null;    
		BufferedWriter csvFileOutputStream = null;
		try {
			File file = new File(outPutPath);
			if (!file.exists()) {
				file.mkdir();
			}
			//定义文件名格式并创建
			csvFile = File.createTempFile(fileName, ".csv", new File(outPutPath));
//			//给文件重命名
//			if(csvFile.exists()){
//				System.out.println("传入的fileName是"+fileName);
//				csvFile.renameTo(new File("c:\\Users\\Administrator\\Desktop\\"+fileName+".csv"));
//				System.out.println("csvFile1:" + csvFile);
//			}
//			String ss = "1,2,3,4\r\n";
//			
			System.out.println("csvFile:" + csvFile);
			// UTF-8使正确读取分隔符"," 
			csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "gbk"), 1024);
			System.out.println("csvFileOutputStream:" + csvFileOutputStream);
			// 写入文件头部 
			for(Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();){
				
				java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
				csvFileOutputStream.write("" + (String) propertyEntry.getValue() != null ? (String) propertyEntry.getValue() : "" + "");
				if(propertyIterator.hasNext()) {
					csvFileOutputStream.write(",");
				}
			}
			csvFileOutputStream.newLine();
			// 写入文件内容 
			for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
				Object row = (Object) iterator.next();
				for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();){
					java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
					csvFileOutputStream.write((String) BeanUtils.getProperty(row,(String) propertyEntry.getKey()));
					if (propertyIterator.hasNext()) {
						csvFileOutputStream.write(",");
					}
				}
				if(iterator.hasNext()){
					csvFileOutputStream.newLine();
				}
			}
			csvFileOutputStream.flush(); 
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				csvFileOutputStream.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return csvFile;
	}
	
	
	/**
	 *     下载文件
	 * @param response
	 * @param csvFilePath
	 * 			文件路径
	 * @param fileName
	 * 			文件名称
	 * @throws IOException
	 * @date 2016-3-4下午03:10:13
	 */
	public static void exportFile(HttpServletResponse response, String csvFilePath, String fileName) 
	 																			throws IOException {
		 response.setContentType("application/csv;charset=UTF-8");    
		 response.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
		 InputStream in = null;
		 OutputStream out = null;
		 try {
			 in = new FileInputStream(csvFilePath);
			 int len = 0;
			 byte[] buffer = new byte[1024];
			 response.setCharacterEncoding("UTF-8");
			 out = response.getOutputStream();
			 while ((len = in.read(buffer)) > 0) {
				 out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
				 out.write(buffer, 0, len);
			 }
		} catch (FileNotFoundException e) {
			System.out.println(e);
		} finally{
			if(in != null||out!=null){
				try {
					out.close();//解决冲突问题
					in.close();
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		} 
	 }
	 
	 /**
	  * 删除该目录filePath下的所有文件
	  * @param filePath
	  *       文件目录路径
	  */
	 public static void deleteFiles(String filePath) {
		 File file = new File(filePath);
		 if (file.exists()) {
			 File[] files = file.listFiles();
			 for (int i = 0; i < files.length; i++) {
				 if (files[i].isFile()) {
					 files[i].delete();
				 }
			 }
		 }
	 }
	 
	 /**
	  * 删除单个文件
	  * @param filePath
	  * 文件目录路径
	  * @param fileName
	  * 文件名称
	  * 
	  */
	 public static void deleteFile(String filePath, String fileName) {
		 File file = new File(filePath);
		 if (file.exists()) {
			 File[] files = file.listFiles();
			 for (int i = 0; i < files.length; i++) {
				 if (files[i].isFile()) {
					 if (files[i].getName().equals(fileName)) {
						 files[i].delete();
						 return;
					 }
				 }
			 }
		 }
	 }
	 
	 /**
	  * 测试数据
	  * @param args
	  * @date 2016-3-4下午03:06:03
	  */
	 @SuppressWarnings("unchecked")
	public static void main(String[] args) {
		 List exportData = new ArrayList<Map>();
		 Map row1 = new LinkedHashMap<String, String>();
		 row1.put("1", "11");
		 row1.put("2", "12");
		 row1.put("3", "13");
		 row1.put("4", "14");
		 exportData.add(row1);
		 row1 = new LinkedHashMap<String, String>();
		 row1.put("1", "21");    
		 row1.put("2", "22");    
		 row1.put("3", "23");    
		 row1.put("4", "24");    
		 exportData.add(row1);
		 LinkedHashMap map = new LinkedHashMap();    
		 map.put("1", "第一列");    
		 map.put("2", "第二列");    
		 map.put("3", "第三列");    
		 map.put("4", "第四列");
		 String path = "c:/export/";    
		 String fileName = "文件导出";    
		 File file = CSVUtil.createCSVFile(exportData, map, path, fileName);    
		 String fileName2 = file.getName();    
		 System.out.println("文件名称:" + fileName2);
	 }
}

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<package name="XXXXcheckAction" namespace="/admin/XXXXcheck" extends="global">
		<action name="*" class="XXXXCheckAction" method="{1}">
		
			<result name="list">list.jsp</result>
			<result name="redBack" type="redirect"></result>
			<result name="refund" type="redirect"></result>
			<result name="lanbu" type="redirect"></result>
			<result name="toList" type="redirect"></result>
			<!-- 文件下载  -->
			<result type="stream" name="success">  
				<!-- 文件对应的流对象,与action中流对象名保持一致 -->
				<param name="inputName">fileInputStream</param>  
				<!-- 文件类型,application/octet-stream是不限制类型 -->
		        <param name="contentType">application/octet-stream</param>  
		        <!-- 发送给客户端的文件名,${fileName} 与action中文件名保持一致-->
		        <param name="contentDisposition">attachment;filename="${fileName}"</param>
		        <!-- 缓冲区大小 -->
		        <param name="bufferSize">2048</param>  
			</result>
		</action>
	</package>
</struts>








  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值