2012-10-31 62 views
8

我遇到了需要將數據導出到.csv文件但不將文件存儲在文件系統中的問題 - 相反,我需要在瀏覽器中簡單地打開文件。導出爲CSV文件並在瀏覽器中打開

我已經寫了下面的代碼將數據寫入到.csv文件:

FileWriter myWriter = new FileWriter("output.csv"); 
myWriter.append(EmployeeCode); 
myWriter.append(','); 
myWriter.append(Band); 
myWriter.append('\n'); 
response.setHeader("Content-Disposition", "attachment; filename=output.csv"); 
response.setContentType("application/ms-excel"); 
response.setCharacterEncoding("UTF-8"); 

我能夠打開一個.csv文件,但它是空的。我的數據沒有填充到它。 請建議我做錯了什麼。

+4

在末尾添加'myWriter.flush(); myWriter.close();'&同時寫入打印屏幕上的相同數據' System.out.println(EmployeeCode +「==」+ Band);'看看你是否正在獲取數據。 –

+0

Fahim, 是的,我正在使用Sys out打印數據。 – user179516

+0

@ user179516我們應該關閉文件編寫器,以便從末尾的流中讀取:) – gks

回答

16

FileWriter將內容寫入output.csv文件中,而不是在響應輸出流中。你應該這樣做:

OutputStream out = response.getOutputStream(); 

得到響應輸出流。

,寫out流中的內容,是這樣的:

response.setContentType("application/ms-excel"); // or you can use text/csv 
response.setHeader("Content-Disposition", "attachment; filename=output.csv"); 
try { 
    // Write the header line 
    OutputStream out = response.getOutputStream(); 
    String header = "EmployeeCode, Band\n"; 
    out.write(header.getBytes()); 
    // Write the content 
    String line=new String(EmployeeCode+","+Band+"\n"); 
    out.write(line.toString().getBytes()); 
    out.flush(); 
} catch (Exception e) { 
    log.error(e); 
} 
+0

我試過這個,但是我得到了FileNotFound錯誤。 – user179516

+0

謝謝一噸丹。我知道了。 – user179516

+0

@ user179516不客氣。 – dan