package com.k.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 文件操参考:http://blog.csdn.net/nihaoqiulinhe/article/details/53838874
*/
public class CsvUtil {
public static boolean hasWrapper = true ;
public static String DATE_FORMAT= "yyyy-MM-dd HH:mm:ss" ;
/**
* 生成为CVS文件
*
* @param <T>
* @param exportData
* 源数据List
* @param fileds
* @param map
* csv文件的列表头map
* @param outPutPath
* 文件路径
* @param fileName
* 文件名称
*/
public static <T> File createCSVFile(List<T> exportData, String[] fileds, Map<String,String> map, String outPutPath,
String fileName) throws Exception {
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));
//
File file = new File(outPutPath);
csvFile = new File( outPutPath,fileName ) ;
if( !csvFile.exists() ){
csvFile.createNewFile() ;
}
// UTF-8使正确读取分隔符","
csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), Util.DEFAULT_CHARSET), 1024);
// 写入文件头部
for ( int i=0; i< fileds.length ;i++ ) {
String key = fileds[i];
Object value = map.get(key) ;
write( csvFileOutputStream ,value!= null ?String.valueOf( value) : "" ,hasWrapper );
if ( i < fileds.length -1 ) {
csvFileOutputStream.write(",");
}
}
csvFileOutputStream.write("\r\n");
// 写入文件内容,
// ============ //第一种格式:Arraylist<实体类>填充实体类的基本信息==================
for (int j = 0; exportData != null && !exportData.isEmpty() && j < exportData.size(); j++) {
T t = (T) exportData.get(j);
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) t.getClass();
String[] contents = new String[fileds.length];
for (int i = 0; fileds != null && i < fileds.length; i++) {
String filedName = getMethodName(fileds[i]);
Method method = clazz.getMethod(filedName);
method.setAccessible(true);
Object obj = method.invoke(t);
String str = null ;
if( obj != null && obj instanceof Date ){
str = DateUtil.getDateTime( (Date)obj ) ;
}else{
str = String.valueOf(obj);
}
if (str == null || str.equals("null"))
str = "";
if( hasWrapper ){
contents[i] = "\""+ str + "\"";
}else{
contents[i] = str;
}
}
for (int n = 0; n < contents.length; n++) {
// 将生成的单元格添加到工作表中
write( csvFileOutputStream ,contents[n] ,false);
if( n < contents.length -1 ){
csvFileOutputStream.write(",");
}
}
csvFileOutputStream.write("\r\n");
}
csvFileOutputStream.flush();
} catch (Exception e) {
throw e ;
} finally {
try {
csvFileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return csvFile;
}
public static <T> File createCSVFile(List<T> exportData, String[] fileds, Map<String,String> map,File csvFile ) throws Exception {
BufferedWriter csvFileOutputStream = null;
try {
if( !csvFile.exists() ){
csvFile.createNewFile() ;
}
// UTF-8使正确读取分隔符","
csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), Util.DEFAULT_CHARSET), 1024);
// 写入文件头部
for ( int i=0; i< fileds.length ;i++ ) {
String key = fileds[i];
Object value = map.get(key) ;
write( csvFileOutputStream ,value!= null ?String.valueOf( value) : "" ,hasWrapper );
if ( i < fileds.length -1 ) {
csvFileOutputStream.write(",");
}
}
csvFileOutputStream.write("\r\n");
// 写入文件内容,
// ============ //第一种格式:Arraylist<实体类>填充实体类的基本信息==================
for (int j = 0; exportData != null && !exportData.isEmpty() && j < exportData.size(); j++) {
T t = (T) exportData.get(j);
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) t.getClass();
String[] contents = new String[fileds.length];
for (int i = 0; fileds != null && i < fileds.length; i++) {
String filedName = getMethodName(fileds[i]);
Method method = clazz.getMethod(filedName);
method.setAccessible(true);
Object obj = method.invoke(t);
String str = null ;
if( obj != null && obj instanceof Date ){
str = DateUtil.getDateTime( (Date)obj ) ;
}else{
str = String.valueOf(obj);
}
if (str == null || str.equals("null"))
str = "";
if( hasWrapper ){
contents[i] = "\""+ str + "\"";
}else{
contents[i] = str;
}
}
for (int n = 0; n < contents.length; n++) {
// 将生成的单元格添加到工作表中
write( csvFileOutputStream ,contents[n] ,false);
if( n < contents.length -1 ){
csvFileOutputStream.write(",");
}
}
csvFileOutputStream.write("\r\n");
}
csvFileOutputStream.flush();
} catch (Exception e) {
throw e ;
} finally {
try {
csvFileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return csvFile;
}
private static void write(BufferedWriter csvFileOutputStream ,String str,boolean hasWrapper ) throws IOException{
if( hasWrapper ){
csvFileOutputStream.write("\""+ str+"\"" );
}else{
csvFileOutputStream.write( str );
}
}
/**
* 将第一个字母转换为大写字母并和get拼合成方法
*/
private static String getMethodName(String origin) {
StringBuffer sb = new StringBuffer(origin);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
sb.insert(0, "get");
return sb.toString();
}
}