java 生成 csv文件

转载: https://blog.csdn.net/nihaoqiulinhe/article/details/53838874
package csvdemo003;

import java.util.LinkedHashMap;

public class CouponCountBean {
	
	private String account_id;
	private String coupon_count;
	private String coupon_money;
	private String phone;
	
	public String getAccount_id() {
		return account_id;
	}
	public void setAccount_id(String account_id) {
		this.account_id = account_id;
	}
	public String getCoupon_count() {
		return coupon_count;
	}
	public void setCoupon_count(String coupon_count) {
		this.coupon_count = coupon_count;
	}
	public String getCoupon_money() {
		return coupon_money;
	}
	public void setCoupon_money(String coupon_money) {
		this.coupon_money = coupon_money;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	/**
	 * 将当前对象封装为Map
	 * @return
	 */
	public LinkedHashMap<String ,String> getMap(){
		LinkedHashMap<String ,String>  map  = new LinkedHashMap<String ,String>();
		map.put("1", phone);
		map.put("2", coupon_count);
		map.put("3", coupon_money);
		return map;
	}
	
	/**
	 * 静态方法:获取csv文件的标题行
	 * @return
	 */
	public static LinkedHashMap<String ,String>  getTitleMap(){
		LinkedHashMap<String ,String>  map  = new LinkedHashMap<String ,String>();
		map.put("1", "phone");
		map.put("2", "coupon_count");
		map.put("3", "coupon_money");
		return map;
	}
	
	

}
package csvdemo003;

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.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件操作
 * 
 * @author lizhiyong
 * @version $Id: CSVUtils.java, v 0.1 2014年7月22日 下午2:19:59 Exp $
 */
public class CSVUtils3 {

	/**
	 * 生成为CVS文件
	 * 
	 * @param exportData
	 *            源数据List
	 * @param map
	 *            csv文件的列表头map
	 * @param outPutPath
	 *            文件路径
	 * @param fileName
	 *            文件名称
	 * @return
	 */
	public static File createCSVFile(List<LinkedHashMap<String, String>> exportData, LinkedHashMap<String, String> titleMap,
			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));  
            System.out.println("csvFile:" + csvFile);  
            // UTF-8使正确读取分隔符","    
            csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(  
                csvFile), "GBK"), 1024);  
            System.out.println("csvFileOutputStream:" + csvFileOutputStream);  
            
            // 写入文件头部-head头 
            for (Iterator propertyIterator = titleMap.entrySet().iterator(); propertyIterator.hasNext();) {  
                java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();  
                csvFileOutputStream.write((String) propertyEntry.getValue() != null ? new String(  
                    ((String) propertyEntry.getValue()).getBytes("GBK"), "GBK") : "");  
                if (propertyIterator.hasNext()) {  
                    csvFileOutputStream.write(",");  
                }  
                System.out.println(new String(((String) propertyEntry.getValue()).getBytes("GBK"),  
                    "GBK"));  
            }  
            
            
            
            
            // 头和体之间的换行
            csvFileOutputStream.write("\r\n");  
            
            
            
            // 写入文件内容-body体     -- 循环list集合
            for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {  
            	
            	// 每个内容是一个LinkedHashMap
            	LinkedHashMap<String,String>    row = (LinkedHashMap) iterator.next();  
            	// 循环LinkedHashMap -- 循环次数同标题次数相同       	
                for (Iterator propertyIterator = titleMap.entrySet().iterator(); propertyIterator.hasNext();) {  
                	// 次值为titleMap的数据 --  取得每一个数据 包含key-val 数据
                    java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();  
                    // 写入val数据
                    csvFileOutputStream.write(   row.get(propertyEntry.getKey())  != null? row.get(propertyEntry.getKey()) : "") ;  
                    // 如果有数据,则继续拼接分隔符","
                    if (propertyIterator.hasNext()) {  
                        csvFileOutputStream.write(",");  
                    }  
                }  
                //如果有新行,则换行
                if (iterator.hasNext()) {  
                    csvFileOutputStream.write("\r\n");  
                }  
            }  
            csvFileOutputStream.flush();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                csvFileOutputStream.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return csvFile;  
    }

	/**
	 * 下载文件
	 * 
	 * @param response
	 * @param csvFilePath
	 *            文件路径
	 * @param fileName
	 *            文件名称
	 * @throws IOException
	 */
	public static void exportFile(HttpServletResponse response, String csvFilePath, String fileName)
			throws IOException {
		response.setContentType("application/csv;charset=GBK");
		response.setHeader("Content-Disposition",
				"attachment;  filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));
		// URLEncoder.encode(fileName, "GBK")

		InputStream in = null;
		try {
			in = new FileInputStream(csvFilePath);
			int len = 0;
			byte[] buffer = new byte[1024];
			response.setCharacterEncoding("GBK");
			OutputStream 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) {
				try {
					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
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void main(String[] args) {

		// 标题
		LinkedHashMap<String, String> titleMap =CouponCountBean.getTitleMap();

		List<LinkedHashMap<String, String>> exportData = new ArrayList<LinkedHashMap<String, String>>();
		for (int i = 0; i < 10; i++) {
			CouponCountBean bean = new CouponCountBean();
			bean.setAccount_id(i + "  id");
			bean.setCoupon_count(i + 10 + "  count");
			bean.setCoupon_money(i + 100 + "  money");
			bean.setPhone(i + 1000 + "  phone");
			exportData.add(bean.getMap());
		}

	 
		String path = "c:/export/";
		String fileName = "文件导出";
		File file = CSVUtils3.createCSVFile(exportData, titleMap, path, fileName);
		String fileName2 = file.getName();
		System.out.println("文件名称:" + fileName2);
	}
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值