ReportViewer - 以编程方式将报告导出到特定位置而不显示保存对话框

ReportViewer - Export report programmatically to a specific location without showing save dialog

我目前有一个 Windows 表单 ReportViewerSSRS 报告中获取信息。

获取信息后,我可以选择将它们导出为 PDF、Word 或 Excel 文档,为此,首先,我需要保存查看文档。

我宁愿采用另一种方式,即将结果导出到特定文件,然后保存文档(如果这是我的选择)。

这可能吗?

您可以处理 ReportViewerReportExport 事件并设置 e.Cancel=true; 然后使用其 LocalReportServerReportRender 方法 属性,将其导出到所需位置。

对 rdlc 报告使用 LocalReport,对 rdl 报告使用 ServerReport。在下面的代码中,我决定使用 属性 使用值 ProcessingMode.

这样,当用户单击 Export 按钮中的可用选项之一时,报告将导出为指定格式,位于您在代码中设置的位置:

private void reportViewer1_ReportExport(object sender, 
    Microsoft.Reporting.WinForms.ReportExportEventArgs e)
{
    e.Cancel = true;
    string mimeType;
    string encoding;
    string fileNameExtension;
    string[] streams;
    Microsoft.Reporting.WinForms.Warning[] warnings;

    Microsoft.Reporting.WinForms.Report report;
    if (reportViewer1.ProcessingMode == Microsoft.Reporting.WinForms.ProcessingMode.Local)
        report = reportViewer1.LocalReport;
    else
        report = reportViewer1.ServerReport;

    var bytes = report.Render(e.Extension.Name, e.DeviceInfo,
                    Microsoft.Reporting.WinForms.PageCountMode.Actual, out mimeType,
                    out encoding, out fileNameExtension, out streams, out warnings);

    var path = string.Format(@"d:\file.{0}", fileNameExtension);
    System.IO.File.WriteAllBytes(path, bytes);


    MessageBox.Show(string.Format("Exported to {0}", path));
}

注意:另外不要忘记使用设计器或代码将 reportViewer1_ReportExport 附加到 ReportExport,如果您忘记了,您将看到对话框。