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

梦想的初衷 提交于 2019-12-01 10:50:32

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!