@Service
public class ReportExportUtil {
/**
* 生成CVS文件
*
* @param dataset 源数据集合
* @param map csv文件的列表头map
* @param fileName 文件名称
* @return
* @throws IOException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
public static <T> void createCSVFile(Collection<T> dataset, LinkedHashMap map, String fileName,HttpServletResponse response)
throws IOException, InvocationTargetException, NoSuchMethodException {
BufferedWriter bufferedWriter = null;
File csvFile = null;
// 定义文件名格式并创建
try {
csvFile = File.createTempFile(fileName, ".csv");
bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"),
1024);
// 写入头部
for (Iterator headIterator = map.entrySet().iterator(); headIterator.hasNext(); ) {
Map.Entry headEntry = (Map.Entry) headIterator.next();
bufferedWriter.write((String) headEntry.getValue() != null ? (String) headEntry.getValue() : "");
if (headIterator.hasNext()) {
bufferedWriter.write(",");
}
}
bufferedWriter.newLine();
Iterator<T> it = dataset.iterator();
while (it.hasNext()) {
T t = (T) it.next();
// 获取类属性
Field[] fields = t.getClass().getDeclaredFields();
String[] csvContent = new String[fields.length];
for (short i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
String fieldType = field.getType().toString();
if ( !isContains(fieldName)&&i == fields.length - 1) {
bufferedWriter.newLine();
}
if (!isContains(fieldName)) {
continue;
}
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
try {
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
Object value = getMethod.invoke(t, new Object[]{});
// 取值并赋给数组
String textvalue = null;
if (value==null){
textvalue = " ";
}else{
if (fieldType.equals("class java.util.Date")) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
textvalue = sdf.format(value);
}else{
textvalue = value.toString();
}
}
bufferedWriter.write(textvalue);
if (i < fields.length - 1) {
bufferedWriter.write(",");
}
if (i == fields.length - 1) {
bufferedWriter.newLine();
}
} catch (Exception e) {
e.getStackTrace();
}
}
bufferedWriter.flush();
}
} finally {
bufferedWriter.close();
}
byte[] b = new byte[1024];
File fileLoad = new File(csvFile.getCanonicalPath());
response.reset();
response.setContentType("application/csv");
String trueCSVName="PaymentReport_" + DateUtils.getCurrentDateTime() + ".csv";
trueCSVName = new String(trueCSVName.getBytes("GBK"), "ISO8859-1");
response.setHeader("Content-Disposition", "attachment; filename=" + trueCSVName);
FileInputStream in = new FileInputStream(fileLoad);
int len = 0;
byte[] buffer = new byte[1024];
response.setCharacterEncoding("UTF-8");
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);
}
in.close();
csvFile.delete();
}
/**
* 下载文件
*
* @param response
* @param csvFilePath 文件路径
* @param fileName 文件名称
*/
public static void exportFile(HttpServletResponse response, String csvFilePath, String fileName) {
response.setContentType("application/csv;charset=UTF-8");
InputStream in = null;
try {
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
in = new FileInputStream(csvFilePath+fileName);
int len = 0;
byte[] buffer = new byte[1024];
response.setCharacterEncoding("UTF-8");
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);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException();
}
}
}
}
public static LinkedHashMap<String,String> getreportHeaders(){
LinkedHashMap map = new LinkedHashMap();
map.put("1", "日期");
map.put("2", "通证编号");
map.put("3", "签发日期");
map.put("4", "持证方");
map.put("5", "到期悦票金额");
return map;
}
/**
* 判断是否是报表字段
* @param field
* @return
*/
public static boolean isContains(String field){
Set reportFields = new HashSet(Arrays.asList("expireDate", "tokenNo","issueDate","toCorpName","amount"));
if (reportFields.contains(field)) {
return true;
}else{
return false;
}
}
}