2012-08-01 61 views
0

我有一個XPage,使用服務器端JavaScript(感謝Russ Maher)創建Excel文件。如果我在瀏覽器中本地運行XPage,我知道如何將它保存到C:驅動器,但不知道如何在服務器上運行時將其保存到用戶計算機上,而無需先將其保存到服務器。以下代碼用於從服務器角度保存它。如何從瀏覽器保存Excel文件到本地驅動器

var fileOut = new java.io.FileOutputStream(directory+fileName); 
xl.write(fileOut); 
fileOut.close(); 

任何想法,我可以指示用戶的驅動器?

回答

0

Paul Calhoun向我發送了一些示例代碼,讓我按照它來生成我想要的電子表格。我不知道他做了什麼,我沒有,但現在,我認爲這是解決方案的核心,只是利用OutputStream而不是FileOutputStream或ByteArrayOutputStream。

// The Faces Context global object provides access to the servlet environment via the external content 
var extCont = facesContext.getExternalContext(); 
// The servlet's response object provides control to the response object 
var pageResponse = extCont.getResponse(); 
//Get the output stream to stream binary data 
var pageOutput = pageResponse.getOutputStream(); 

// Set the content type and headers 
pageResponse.setContentType("application/x-ms-excel"); 
pageResponse.setHeader("Cache-Control", "no-cache"); 
pageResponse.setHeader("Content-Disposition","inline; filename=" + fileName); 
//Write the output, flush the buffer and close the stream 
wb.write(pageOutput); 
pageOutput.flush(); 
pageOutput.close(); 

// Terminate the request processing lifecycle. 
facesContext.responseComplete(); 

我會很樂意提供幫助,如果別人遇到這個問題,並希望由別人問的時候,我就明白了更多的什麼不同的是工作....

1

而不是寫Excel工作簿到一個FileOutputStream的,你應該把它寫一個ByteArrayOutputStream:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
xl.write(outputStream); 

您可能需要使用XAgent創建輸出,然後從你的XPage鏈接到XAgent。也許this blog entry by Declan Lynch結合this answer on how to do it in a servlet可以引導你在正確的方向。

+0

每是正確的。查看OpenNTF上的XSnippets中的XAgent代碼片段。它提供輸出流。因此,而不是創建自己的流將其作爲參數傳遞給您的方法。內容處置標題然後可以確定文件名稱。請記住用戶需要確認保存。還可以看看Apache POI以獲得更高級的Excel輸出功能 – stwissel 2012-08-02 00:20:24

+0

感謝Per會檢查出來。 @stwissel我正在使用Apache POI,但我是一名真正的業餘愛好者,剛剛採用了Russ Maher的實施並稍加擴展。 – 2012-08-02 13:43:47

相關問題