1. 程式人生 > >java 匯出csv格式(支援list的實體類)

java 匯出csv格式(支援list的實體類)

         做的網頁專案,要匯出pdf使用itext工具,要是excel就使用jxl的jar包,匯出csv格式的話,就可以使用如下工具類,參考的博主是http://blog.csdn.net/xuxu198899223/article/details/38079885?utm_source=tuicool&utm_medium=referral,他支援傳入的資料是map的形式的,實際在專案中不太常用,一般都是實體類的Arraylist形式,這樣支援擴充套件,如下我在他的基礎上修改的程式碼(保留他原來的程式碼):

     1.實體類:

/**
 * 
 * @author ALLONE
 *
 */
public class BankWageMonth {
	private String id;//

	private String number;//

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}

}
    2.工具類,匯出csv格式:
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.lang.reflect.Method;
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 jxl.write.Label;

import org.apache.commons.beanutils.BeanUtils;

/**
 * 檔案操作
 * 
 * @author qiulinhe
 * @version 2016年12月23日14:21:39
 */
public class CsvUtil {

	/**
	 * 生成為CVS檔案
	 * 
	 * @param exportData
	 *            源資料List
	 * @param fileds
	 * @param map
	 *            csv檔案的列表頭map
	 * @param outPutPath
	 *            檔案路徑
	 * @param fileName
	 *            檔名稱
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static File createCSVFile(List exportData, String[] fileds,
			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));
			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 ? 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");
			// 寫入檔案內容,
			// ============ //第一種格式:Arraylist<實體類>填充實體類的基本資訊==================
			for (int j = 0; exportData != null && !exportData.isEmpty()
					&& j < exportData.size(); j++) {
				BankWageMonth t = (BankWageMonth) exportData.get(j);
				Class clazz = t.getClass();
				String[] contents = new String[fileds.length];
				for (int i = 0; fileds != null && i < fileds.length; i++) {
					String filedName = toUpperCaseFirstOne(fileds[i]);
					Method method = clazz.getMethod(filedName);
					method.setAccessible(true);
					Object obj = method.invoke(t);
					String str = String.valueOf(obj);
					if (str == null || str.equals("null"))
						str = "";
					contents[i] = str;

				}

				for (int n = 0; n < contents.length; n++) {
					// 將生成的單元格新增到工作表中
					csvFileOutputStream.write(contents[n]);
					csvFileOutputStream.write(",");

				}
				csvFileOutputStream.write("\r\n");
			}

			// ============ //第二種格式:Arraylist<map>填充實體類的基本資訊==================
			// 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()) != null ? (String)
			// 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) {
		// 獲取農商銀行的資料:true代表是農商
		// =======改成list的格式,支援(Arraylist傳入實體類的形式),改造的方法============
		ArrayList<BankWageMonth> bankWageList = new ArrayList<BankWageMonth>();
		BankWageMonth bankWage = new BankWageMonth();
		bankWage.setId("123");
		bankWage.setNumber("2016rz0001");

		BankWageMonth bankWage2 = new BankWageMonth();
		bankWage2.setId("124");
		bankWage2.setNumber("2016rz0002");

		bankWageList.add(bankWage);
		bankWageList.add(bankWage2);

		// =======改成list的格式(支援map的形式),原作者的方法============

		// 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 = "D://export//";
		String fileName = "檔案匯出";
		String fileds[] = new String[] { "id", "number" };// 設定列英文名(也就是實體類裡面對應的列名)
		File file = CsvUtil.createCSVFile(bankWageList, fileds, map, path,
				fileName);
		String fileName2 = file.getName();
		System.out.println("檔名稱:" + fileName2);
	}

	/**
	 * 將第一個字母轉換為大寫字母並和get拼合成方法
	 * 
	 * @param origin
	 * @return
	 */
	private static String toUpperCaseFirstOne(String origin) {
		StringBuffer sb = new StringBuffer(origin);
		sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
		sb.insert(0, "get");
		return sb.toString();
	}
}