2009年11月12日 星期四

Cliend-Side Report 匯出 Excel, PDF

一般來說,我不喜歡把工具列顯示給使用者看,主要是因為工具列中在【匯出】的下拉式選單中會出現excel即pdf兩種格式,我不想要把這樣的資訊給使用者知道,因為使用者的欲望總是無窮,看到這兩個之後,就會問說:【下拉式選單中能幫我多一個word,tiff,etc】,所以可以的話儘可能不要讓使用者看到。

而在ReportViewer的元件中,有一個屬性叫做【ShowToolBar】,你可以設定為false,則在呈現的時候ToolBar則會整個隱藏,如下圖

ShowToolBar=True的情形

ShowToolBar=False的情形
不過如果你捨不得將整個ToolBar都隱藏的話,在ReoprtViewer的屬性中有一個部份是針對ToolBar來做細微設定,如下圖

如果只想要隱藏匯出功能的話,可以把設定ShowExportControls=False 即可,設定完之後記得把剛剛的ShowToolBar=False -> ShowToolBar=True,則出現結果如下圖

當把匯出的選項從Toolbar關掉之後,如果需要自己撰寫匯出的功能其實也很簡單,有興趣可以參考LocalReport.Render 方法,我們在該aspx頁面中加入一個Button來產生excel,然後針對其撰寫Click事件之程式碼如下
Warning[] warnings;
        string[] streamids;
        string mimeType;
        string encoding;
        string extension;

        byte[] bytes = ReportViewer1.LocalReport.Render(
           "Excel", null, out mimeType, out encoding, out extension,
           out streamids, out warnings);

        Response.Clear();
        Response.AddHeader("Content-Disposition", "attachment; filename=sample.xls");
        Response.AddHeader("Content-Length", bytes.Length.ToString());
        Response.ContentType = "application/octet-stream";
        Response.OutputStream.Write(bytes, 0, bytes.Length); 

另一個產生Pdf的按鈕事件之程式碼如下
Warning[] warnings;
   string[] streamids;
   string mimeType;
   string encoding;
   string extension;

   byte[] bytes = ReportViewer1.LocalReport.Render(
        "Pdf", null, out mimeType, out encoding, out extension,
         out streamids, out warnings);

   Response.Clear();
   Response.AddHeader("Content-Disposition", "attachment; filename=sample.pdf");
   Response.AddHeader("Content-Length", bytes.Length.ToString());
   Response.ContentType = "application/octet-stream";
   Response.OutputStream.Write(bytes, 0, bytes.Length);
 

再次瀏覽該頁面,如下

分別點選【Export Excel】及【Export Pdf】按鈕,則頁面會各自出現另存新檔畫面,我們將檔案儲存下來之後,觀看excel及pdf之結果如下

Excel

PDF

結論:
一般來說如果使用者只是直接想匯出檔案,我甚至不會給使用者看到ReportViewer的查詢畫面,例如如果要列印的東西是證書,其實是不需要先給使用者看該證書的ReportViewer畫面,只需要直接匯出該Pdf之結果供使用者列印即可,如果是這種需求,則可以將上述產生Pdf的程式碼貼到Page Load的Event中即可

沒有留言: