导出CSV文件

 

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.vservice.es.encaplables.LableForEnCh;

public class CSVUtils {

	private static final Logger logger = Logger.getLogger(CSVUtils.class);

	static Map<String, String> titles = new HashMap<String, String>();

	static {
		
		// 首行列对应的中文名
		Map<String, String> titleCName = new HashMap<String, String>();
		titleCName.put("name", "姓名");
		titleCName.put("gender", "性别");
		
		// 列排序用
		List<String> titleList = new ArrayList<String>();
		titleList.add("name");	 // 姓名	
		titleList.add("gender");  // 性别			
		
		List<String> titleNameList = new ArrayList<String>();
		String lableName = null;
		for (String string : titleList) {
			lableName = titleCName.get(string);
			titleNameList.add(StringUtils.isNotBlank(lableName) ? lableName : "");
		}

		for (int i = 0; i < titleList.size(); i++) {
			// 根据titleList先后顺序排序
                        titles.put(i + titleList.get(i), titleNameList.get(i));
		}
	}

	public static boolean createCSVFile(List<JSONObject> jsonArray, String exportPath) {
		long begin = System.currentTimeMillis();

		File csvFile = null;
		BufferedWriter csvWtriter = null;
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		try {
			String ePath = exportPath + File.separator + System.nanoTime() + ".csv";
			csvFile = new File(ePath);
			fos = new FileOutputStream(csvFile);
			osw = new OutputStreamWriter(fos);
			// bom utf-8格式保存文件
			osw.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));  
			
			csvWtriter = new BufferedWriter(osw, 1024);
			
			String[] tilteKeys = getTilteKeys();
			StringBuffer head = new StringBuffer();
			StringBuffer rowS = null;

			for (int i = 0; i < jsonArray.size(); i++) {
				if (null == rowS) {
					rowS = new StringBuffer();
				}
				JSONObject obj = jsonArray.get(i);
				for (int j = 0; j < tilteKeys.length; j++) {
					if (i == 0) {
						String tille = titles.get(j + tilteKeys[j]);
						head.append("\"").append(tille).append("\",");
						if (j == tilteKeys.length - 1) {
							csvWtriter.write(head.toString());
							csvWtriter.newLine();
						}
					}
 
					String title = (String) tilteKeys[j];
					String value = obj.getString(title);
					if (StringUtils.isNotBlank(value) && StringUtils.isNumeric(value)) {
						value = value + "\t";
					}
					rowS.append("\"").append(StringUtils.isNotBlank(value) ? value : "").append("\",");
					if (j == tilteKeys.length - 1) {
						csvWtriter.write(rowS.toString());
						csvWtriter.newLine();
						rowS = null;
					}
				}
			}
			csvWtriter.flush();
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(csvWtriter);
			IOUtils.closeQuietly(fos);
			IOUtils.closeQuietly(osw);
			long end = System.currentTimeMillis();
			logger.info("export use time :" + (end - begin) + "ms");
		}

		return false;
	}
	
	private static String getNum(String str) {
		str = str.trim();
		String num = "";
		if (str != null && !"".equals(str)) {
			for (int i = 0; i <= 3; i++) {
				if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
					num += str.charAt(i);
				}
			}
		}
		return num;
	}

	private static String[] getTilteKeys() {
		Object[] keys = titles.keySet().toArray();
		String[] tilteKeys = new String[keys.length];
		for (int i = 0; i < keys.length; i++) {
			String temp = keys[i].toString();
			String numStr = getNum(temp);
			int orderNum = Integer.valueOf(numStr);
			tilteKeys[orderNum] = temp.substring(numStr.length());
		}
		return tilteKeys;
	}

	public static void main(String args[]) {
		try {
			List<JSONObject> listData = new ArrayList<JSONObject>();
			JSONObject vo = new JSONObject();
			vo.put("gender", "男");
			vo.put("name", "李斯");
			listData.add(vo);

			String path = "D:/006_test/";
			File file = new File(path);
			if (!file.exists()) {
				if (file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}
				file.createNewFile();
			}

			createCSVFile(listData, path);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


  

猜你喜欢

转载自lingzhi927.iteye.com/blog/2384170