ReportViewer - Export report programmatically to a

2019-05-25 05:17发布

I currently have a Windows Forms ReportViewer that fetches information from an SSRS report.

When the information is fetched I have the option to export them to a PDF, Word or Excel document, to do this, first, I need to save to see the document.

I would rather have it the other way, which is, export the results to a specific file and then, save the document if that's my choice.

Is this possible?

1条回答
太酷不给撩
2楼-- · 2019-05-25 05:34

You can handle ReportExport event of ReportViewer and set e.Cancel=true; then using Render method of its LocalReport or ServerReport property, export it to desired location.

Use LocalReport for rdlc reports and ServerReport for rdl reports. In below code I decided to use the property using value of ProcessingMode.

This way, when the user clicks on one of available options in Export button, the report will be exported to the specified format at the location which you set in code:

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));
}

Note: Also don't forget to attach reportViewer1_ReportExport to ReportExport using designer or code, if you forget you will see the dialog.

查看更多
登录 后发表回答