import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.youku.ad.stat.dao.base.BaseEntity;
import com.youku.ad.stat.dao.entity.basic.UserEty;
public class CsvExportor{
private static final Logger logger = Logger.getLogger(CsvExportor.class);
// private static final String path ="/opt/rev/cvs/";
private static final String csvFilePath ="D://csv//";
public static CsvExportor getExportor() {
return new CsvExportor();
}
public void export(HttpServletRequest request, HttpServletResponse response,Object baseDao, String countMethod, String dataMethod, BaseEntity paramObj, String title, String fileName, ExtLimit limit) throws Exception {
String[] exp_column_names = limit.getExp_column_names().split(",");
String[] exp_column_indexs = limit.getExp_column_indexs().split(",");
// doExportCSV(request, response, baseDao, countMethod, dataMethod, paramObj, title, fileName, exp_column_names, exp_column_indexs);
doExportCSVZip(request, response, baseDao, countMethod, dataMethod, paramObj, title, fileName, exp_column_names, exp_column_indexs);
}
public void doExportCSV(HttpServletRequest request, HttpServletResponse response, Object baseDao, String countMethod, String dataMethod, BaseEntity paramObj, String title, String fileName, String[] exp_column_names, String[] exp_column_indexs )throws Exception {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
if (fileName == null || "".equals(fileName)){
fileName = sf.format(new Date());
}
// int count = (Integer) EntityReflect.invokeMethod(baseDao, countMethod, paramObj);
// 生成数据
String headName = buildTableHeader(exp_column_names);
StringBuilder dataStr = new StringBuilder();
// if(count > 0) {
// int startOffset = 0;
// int pageSize = 1000;
// if (paramObj.getExtLimit() == null) {
// ExtLimit limit = new ExtLimit();
// paramObj.setExtLimit(limit);
// }
// paramObj.getExtLimit().setLimit(pageSize);
// while (startOffset < count) {
// paramObj.getExtLimit().setStart(startOffset);
@SuppressWarnings("unchecked")
List<Object> dataList = (List<Object>) EntityReflect.invokeMethod(baseDao, dataMethod, paramObj);
// 生成数据
dataStr.append(buildDataStr(dataList,exp_column_indexs));
// startOffset += pageSize;
// logger.error(startOffset);
// }
// }
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",(new StringBuilder()).append("attachment; filename=\"").append(new String(fileName.getBytes("GBK"), "ISO8859_1")).append(".csv").append("\" ").toString());
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
try
{
OutputStream fos = response.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(fos, "gbk");
BufferedWriter bw = new BufferedWriter(writer);
bw.write((new StringBuilder()).append(headName).toString());
bw.newLine();
bw.write((new StringBuilder()).append(dataStr).toString());
bw.newLine();
bw.flush();
bw.close();
}
catch (Exception e){
logger.error(e);
}
}
public void doExportCSVZip(HttpServletRequest request, HttpServletResponse response, Object baseDao, String countMethod, String dataMethod, BaseEntity paramObj, String title, String fileName, String[] exp_column_names, String[] exp_column_indexs )throws Exception {
// SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
// if (fileName == null || "".equals(fileName)){
// fileName = sf.format(new Date());
// }
// 生成数据
String headName = buildTableHeader(exp_column_names);
StringBuilder dataStr = new StringBuilder();
@SuppressWarnings("unchecked")
List<Object> dataList = (List<Object>) EntityReflect.invokeMethod(baseDao, dataMethod, paramObj);
dataStr.append(buildDataStr(dataList,exp_column_indexs));
/**
* 创建csv文件到服务器指定位置
* 生成.zip文件
* 导出到客户端
* 删除目录下所有的文件
*/
UserEty userEty = (UserEty) request.getSession().getAttribute("UserEty");
int userId = userEty.getId();
String path = csvFilePath+userId;
createFile(path);
createCsvFile(path,headName,dataStr);
String zipFileNameUrl = craeteZipPath(path);
downloadFile(request, response, zipFileNameUrl);
File file = new File(path);
deleteCvsPath(file);
File zipfile = new File(zipFileNameUrl);
deleteCvsPath(zipfile);
}
public static boolean createCsvFile(String path,String headerName,StringBuilder datastr){
boolean isSucess=false;
File file = new File(path+"//data.csv");
FileOutputStream out=null;
OutputStreamWriter osw=null;
BufferedWriter bw=null;
try {
out = new FileOutputStream(file);
osw = new OutputStreamWriter(out);
bw =new BufferedWriter(osw);
bw.write((new StringBuilder()).append(headerName).toString());
bw.newLine();
bw.append(datastr).append("\r");
isSucess=true;
} catch (Exception e) {
isSucess=false;
}finally{
if(bw!=null){
try {
bw.close();
bw=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(osw!=null){
try {
osw.close();
osw=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
out=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return isSucess;
}
/**
* 生成.zip文件;
* @param path
* @throws IOException
*/
public String craeteZipPath(String path) throws IOException{
ZipOutputStream zipOutputStream = null;
String url = path+".zip";
File file = new File(url);
zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
File[] files = new File(path).listFiles();
FileInputStream fileInputStream = null;
byte[] buf = new byte[1024];
int len = 0;
if(files!=null && files.length > 0){
for(File excelFile:files){
String fileName = excelFile.getName();
fileInputStream = new FileInputStream(excelFile);
//放入压缩zip包中;
zipOutputStream.putNextEntry(new ZipEntry(path + "/"+fileName));
//读取文件;
while((len=fileInputStream.read(buf)) >0){
zipOutputStream.write(buf, 0, len);
}
//关闭;
zipOutputStream.closeEntry();
if(fileInputStream != null){
fileInputStream.close();
}
}
}
if(zipOutputStream !=null){
zipOutputStream.close();
}
return url;
}
/**
* 创建文件夹;
* @param path
* @return
*/
public static String createFile(String path){
File file = new File(path);
//判断文件是否存在;
if(!file.exists()){
//创建文件;
boolean bol = file.mkdirs();
if(!bol){
logger.error(path+" 路径创建失败!");
}
}else{
logger.error(path+" 文件已经存在!");
}
return path;
}
/**
* 创建第一行列名
* @param headNameArr
* @return
*/
private String buildTableHeader(String[] headNameArr) {
StringBuilder strb = new StringBuilder();
for(int i=0;i < headNameArr.length; i++){
strb.append(new StringBuilder()).append("\"").append(headNameArr[i]).append("\",").toString();
}
return strb.toString().substring(0,strb.length()-1);
}
/**
* 创建数据量列
* @param dataList
* @param exp_column_indexs
* @return
*/
private String buildDataStr(List<Object> dataList,String[] exp_column_indexs){
if (dataList == null || dataList.size() <= 0)
return "";
StringBuilder strb = new StringBuilder();
for (Iterator<Object> i$ = dataList.iterator(); i$.hasNext(); strb.append("\n")) {
Object vo = i$.next();
for (int j = 0; j < exp_column_indexs.length; j++) {
Object cellValue = EntityReflect.getObjectProperty(vo, exp_column_indexs[j]);
if (cellValue == null) {
cellValue ="";
} else {
if (cellValue instanceof java.util.Date) {
cellValue = new SimpleDateFormat("yyyy-MM-dd").format(cellValue);
}
else if(cellValue instanceof java.lang.Double) {
cellValue = (Double)cellValue;
}
else if(cellValue instanceof java.lang.Integer) {
cellValue = (Integer)cellValue;
}
else if(cellValue instanceof java.lang.Float) {
cellValue = (Float)cellValue;
}
else {
cellValue = cellValue.toString();
}
}
if(j == exp_column_indexs.length){
//最后一行
strb.append((new StringBuilder()).append("\"").append(cellValue).append("\"").toString());
}else{
strb.append((new StringBuilder()).append("\"").append(cellValue).append("\",").toString());
}
}
}
return strb.toString();
}
/**导出
* @param response
* @param fileName
* @return
* @throws IOException
*/
public static void downloadFile(HttpServletRequest request,HttpServletResponse response,String url)
throws IOException {
//获取服务其上的文件名称
StringBuffer filename = new StringBuffer();
filename.append(url);
File file = new File(filename.toString());
String name = "data.zip";
StringBuffer sb = new StringBuffer();
sb.append("attachment; filename=").append(name);
response.setHeader("Expires", "0");
response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setContentType("application/x-msdownload;charset=UTF-8");
response.setHeader("Content-Disposition", new String( sb.toString().getBytes(), "ISO8859-1"));
//将此文件流写入到response输出流中
FileInputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int i = -1;
while ((i = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, i);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
/**
* 删除目录下所有的文件;
* @param path
*/
public static boolean deleteCvsPath(File file){
String[] files = null;
if(file != null){
files = file.list();
}
if(file.isDirectory()){
for(int i =0;i<files.length;i++){
deleteCvsPath(new File(file,files[i]));
}
}
return file.delete();
}
}
|