Dot-Net
為 ReportViewer (rdlc) 創建自定義導出到 Excel
我有興趣在 ReportViewer 中為我的報告創建自定義導出到 Excel 選項。這主要是因為我想要禁用 pdf 並且我通過以下方式做到了:
ReportViewer1.ShowExportControls = false;由於無法在 ReportViewer 中禁用任何特定的導出功能(例如 pdf 但不是 excel)。下面是我的(稍微)修改的程式碼。理想情況下,我想要類似於以前的導出選項的東西,我可以將文件保存到我想要的任何位置。
編輯:程式碼有效,但我需要如何修改 Filestream 以便我可以提示使用者而不是自動保存文件,以便他們可以保存到他們想要的任何位置?
protected void btnExportExcel_Click(object sender, EventArgs e) { 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); FileStream fs = new FileStream(@"c:\output.xls", FileMode.Create); fs.Write(bytes, 0, bytes.Length); fs.Close(); }
我根據 Microsoft 在 ReportViewer 上的文件和一些 Google 搜尋將其放在一起,以防有人遇到與我類似的問題:
protected void ExportExcel_Click(object sender, EventArgs e) { Warning[] warnings; string[] streamids; string mimeType; string encoding; string extension; string filename; byte[] bytes = ReportViewer1.LocalReport.Render( "Excel", null, out mimeType, out encoding, out extension, out streamids, out warnings); filename = string.Format("{0}.{1}", "ExportToExcel", "xls"); Response.ClearHeaders(); Response.Clear(); Response.AddHeader("Content-Disposition", "attachment;filename=" + filename); Response.ContentType = mimeType; Response.BinaryWrite(bytes); Response.Flush(); Response.End(); }
請注意……接受的答案將呈現為原始海報要求的 XLS 文件。
但是,您現在也可以導出到 XLSX。您必須將方法的
format參數從 更改為。Render()"Excel"``"EXCELOPENXML"要獲得可能值的完整列表,您可以呼叫
ReportViewer1.LocalReport.ListRenderingExtensions(). 當我在我的報表查看器實例上執行它時,我得到了這些可能的選項:
"Excel""EXCELOPENXML""IMAGE""PDF""WORD""WORDOPENXML"我發現很難確定您需要為格式傳遞什麼。如果你問我,MSDN 對此的記錄很差。