package com.ericsson.jigsaw.test.management.quality.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
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 org.apache.log4j.Logger;
public class CsvUtils {
private static Logger logger = Logger.getLogger(CsvUtils.class);
public static File createCSVFile(List exportData, LinkedHashMap rowMapper,
String outPutPath, String filename) {
File csvFile = null;
BufferedWriter csvFileOutputStream = null;
try {
csvFile = new File(outPutPath + filename + ".csv");
// csvFile.getParentFile().mkdir();
File parent = csvFile.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
csvFile.createNewFile();
// GB2312浣挎纭邋殓","
csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(csvFile), "GB2312"), 1024);
// 邋ユ浠跺ご楱
for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator
.hasNext();) {
java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
.next();
csvFileOutputStream.write("\""
+ propertyEntry.getValue().toString() + "\"");
if (propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
}
csvFileOutputStream.newLine();
// 邋ユ浠跺瀹?
for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
Map row = (Map) iterator.next();
for (Iterator propertyIterator = rowMapper.entrySet()
.iterator(); propertyIterator.hasNext();) {
java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
.next();
csvFileOutputStream.write("\""
+ row.get(propertyEntry.getKey().toString())
+"\"");
// + BeanUtils.getProperty(row,
// propertyEntry.getKey().toString())
// +propertyEntry.getValue().toString() + "\"");
if (propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
}
if (iterator.hasNext()) {
csvFileOutputStream.newLine();
}
}
csvFileOutputStream.flush();
} catch (Exception e) {
logger.error("Exception", e);
} finally {
try {
csvFileOutputStream.close();
} catch (IOException e) {
logger.error("IOException", e);
}
}
return csvFile;
}
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);
List propertyNames = new ArrayList();
LinkedHashMap map = new LinkedHashMap();
map.put("1", "Row1");
map.put("2", "Row2");
map.put("3", "Row3");
map.put("4", "Row4");
CsvUtils.createCSVFile(exportData, map, "./", "tmp");
}
}
Java 写 CSV文件
最新推荐文章于 2024-08-26 18:54:08 发布