zoukankan      html  css  js  c++  java
  • (转)Export .NET MSChart to Excel/PDF Using Report Viewer 2010

    Export .NET MSChart to Excel/PDF Using Report Viewer 2010

    By santosh poojari2 Oct 2011
     
     
     

    Table of Contents

    1. Overview
    2. Case Study/Problem Statement
    3. Solution Statement
    4. Prerequisites
    5. How to get started?
    6. Few Twists and Turns (Tips and Tricks)
    7. Conclusion

    Overview

    The business requirement to have reports in Microsoft Office tool has always been a challenge and a need. There is no clear cut solution so as to have Excel, PDF or Word component from Microsoft ASP.NET toolkit to be used as a control. To fulfill our needm we’ve an option to use Microsoft reporting services such as Crystal report or report viewer control where we can create a report using these tools and can easily have all export or print features in build.

    Case Study/Problem Statement

    But what if we already spend a considerable amount of cost and effort in creating reports which do not have these export features. In our case, it happened so we already created the reports in primitive ASP.NET web pages using gridview, repeater and normal HTML controls. These reporting web pages consist of Microsoft .NET charting components, images and data in tables, etc. Now we got a requirement from the client to provide a feature to export these HTML reports in Excel, Word and PDF. We tried all options available online to render the .NET chart controls into Excel but all were in vain. Finally we thought of making use of Report viewer control redistributable 2010 but again to redevelop all the web pages/code components and migrating it into report viewer involves effort. We were running out of time and we thought of an approach of using report viewer EnableExternalImage property.

    Solution Statement

    What we can achieve?

    • We can save Microsoft .NET chart as image and can export it in report viewer RDLC.
    • We can export web page as is in report viewer.
    • Some AXD files format do not export seamlessly in Word, Excel and PDF. For such cases, we can leverage report viewer export function.

    Prerequisites

    How to Get Started?

    1. Create Web solution. Add one web page aspx. Drag and drop Report viewer web control.
    2. Add property EnableExternalImage=true.

    3. Add property localpath=.
    4. Add New Item, RDLC file.
    5. Drag and drop Image control from toolbox into RDLC file.
    6. Go to View menu. Select Report Data option Refer Fig 2.

    7. Add one report parameter. Refer to Fig 2.

    8. Add one sample image in solution and give the reference of report parameter in its function expression. Also select external Image. Refer Fig Note: This is where we create a binding- bridge between aspx source image(path) to report viewer Image Control. Using report parameter, we pass file path details from aspx and image gets embedded into report viewer’s image control container.

      Select Image source external for given Image control.

      Assign the report parameter path in function expression.

    9. Moving on to Code Behind. It’s time to write few lines of the code where we set report parameter and invoke report viewer rendering engine. Write the following code under page_load.
      protected void Page_Load(object sender, EventArgs e)
      {
          if (!IsPostBack)
          {
              Microsoft.Reporting.WebForms.ReportParameter[] ReportParameters = 
      			new Microsoft.Reporting.WebForms.ReportParameter[1];
                  ReportParameters[0] = 
      		new Microsoft.Reporting.WebForms.ReportParameter
      		("ReportParameter1", file:///+
      			Server.MapPath("MemoryStreamImage.JPG"));
                  ReportViewer1.LocalReport.SetParameters(ReportParameters);
          }
      }
    10. ***Most important point to be taken care of; ensure to add script manager in master page as report viewer component default works in asynchronous Ajax mode. Else you will get the below runtime error.

    11. Press Ctrl+F5 to view the output.

    ***Few Twists and Turns (Tips and Tricks)

    1. If you have Microsoft chart component and you want to get this exported into Excel, PDF and Word, use the below code. Save the Microsoft .NET chart object in memory or some server path. Pass this path as input parameter values to report parameter of report viewer control.

      public void ExportChart(Chart chart)
      { 
          MemoryStream image = new MemoryStream();
          chart.SaveImage(image, ChartImageFormat.Png);
      
          Response.ContentType = "image/png";
          Response.AppendHeader("Content-Disposition",
                      String.Format
      		("attachment; filename={0}.png", Page.Title.Replace(" ", "_")));
          Response.OutputStream.Write(image.ToArray(), 0, (int)image.Length); }
    2. The above implementation approach renders the content in report viewer and end users need to select options to export PDF, Word or Excel. We can twig the above code and include the below snippet to directly open up the PDF /Word or Excel. Check out the sample code below to do this:
        ReportViewer1.LocalReport.DataSources.Clear();
                 ReportViewer1.LocalReport.ReportPath = "report1.rdlc";
      
                 List<microsoft.reporting.webforms.reportparameter> _ParamList = 
      		new List<microsoft.reporting.webforms.reportparameter>();
                 ReportViewer1.LocalReport.EnableExternalImages = true;
                  objReportParameter.Add(new Microsoft.Reporting.WebForms.ReportParameter
      				("ImagePath", "/Images/Sample.JPG"));
      
                 ReportViewer1.LocalReport.SetParameters(objReportParameter);
                 ReportViewer1.DataBind();
                  Microsoft.Reporting.WebForms.Warning[] warnings;
                  string[] streamids;
                  string mimeType;
                  string encoding;
                  string extension;
      
       string deviceInfo = "<deviceinfo>" +
                                          "  <outputformat>PDF</outputformat>" +
                                          "  <pagewidth>8.5in</pagewidth>" +
                                          "  <pageheight>11in</pageheight>" +
                                          "  <margintop>0.5in</margintop>" +
                                          "  <marginleft>0.25in</marginleft>" +
                                          "  <marginright>0.25in</marginright>" +
                                          "  <marginbottom>1in</marginbottom>" +
                                          "</deviceinfo>";
      byte[]writeBinaryBytes = new byte[0];
      writeBinaryBytes = ReportViewer1.LocalReport.Render
      	("PDF", deviceInfo, out mimeType, out encoding, out extension, 
      	out streamids, out warnings);
      
                  HttpContext.Current.Response.Buffer = true;
                  HttpContext.Current.Response.AddHeader
      		("content-disposition", "attachment; filename=" + "San.pdf");
                  HttpContext.Current.Response.ContentType = "application/octet-stream";
                  HttpContext.Current.Response.BinaryWrite(writeBinaryBytes);
                  HttpContext.Current.Response.Flush(); 

    Conclusion

    Hope the above approach/solution gives you some directions whenever you come across a similar problem statement.

    License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    About the Author

    santosh poojari
    Technical Lead 
    India India
    He is presently working as tech arch in one of the leading IT company.He has total 10 years of experience in C#.net. He is a B.E graduate in Computers from Bombay University. 
     
    Most of his experiences are in designing architect for end to end solutions. His interest areas are WCF,Spring.net,Architecture- Model View Presenter,UML,Webservice,Performance Engineering/tuning,Design patterns,Generics,Enterprise Library,Regular expressions,Silverlight and WWF.
    www.santoshpoojari.blogspot.com
  • 相关阅读:
    python爬虫统计上证指数周、月涨跌现象
    python每日一题:采用正则表达式,beautifulsoap,xpath爬取网站数据
    谈股市与月份的关系
    python之正则表达式
    python每日一题:使用代理服务器爬虫
    python之cookie使用
    python每日一题:爬虫入门之利用xpath查找网页元素节点
    python每日一题:制作网页,与女朋友的点点滴滴
    【Java基础】Java11 新特性
    【Java基础】Java10 新特性
  • 原文地址:https://www.cnblogs.com/z1971/p/3133613.html
Copyright © 2011-2022 走看看