日期:2014-05-19 浏览次数:20639 次
public void downloadCsv(List<RepairCatalogSearchResultsVO> rowDataList) throws CROSException{
try{
/* File file = new File("D:csv/result/results.csv");
FileOutputStream out = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(out);
BufferedWriter bw = new BufferedWriter(osw);*/
ServletOutputStream servletOutputStream = null;
FileInputStream input = null;
File file = null;
FileOutputStream out = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
//insert data
String filePath = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRealPath("/")
+ "WEB-INF\\" + System.currentTimeMillis() + "_" + "results.csv";
out = new FileOutputStream(filePath);
osw = new OutputStreamWriter(out);
bw = new BufferedWriter(osw);
bw.write("ATA");
bw.write(",");
bw.write("componentDesc");
bw.write(" ") ;
bw.newLine();
Iterator<RepairCatalogSearchResultsVO> ite = rowDataList.iterator();
while (ite.hasNext()) {
RepairCatalogSearchResultsVO vo = ite.next();
bw.write(vo.getAtaNum());
bw.write(",");
bw.write(vo.getComponentDesc());
bw.write(" ") ;
bw.newLine();
}
//close
out.flush();
out.close();
//以下代码是用来下载文件时,由用户选择保存的地址。
file = new File(filePath);
HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
servletOutputStream = httpServletResponse.getOutputStream();
httpServletResponse.setHeader("Content-disposition",
"attachment; filename=" + "results.csv");
httpServletResponse.setContentLength((int) file.length());
httpServletResponse.setContentType("application/x-download");
httpServletResponse.setContentType("application/csv");
byte[] buffer = new byte[1024];
int flag = 0;
input = new FileInputStream(file);
while ((flag = input.read(buffer)) > 0) {
servletOutputStream.write(buffer, 0, flag);
}
servletOutputStream.flush();
bw.close();
osw.close();
out.close();
}
catch(Exception e){
e.printStackTrace() ;
}
}