Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / Office

Exporting a DataGridView to an Excel/PDF/image file by using Reporting Services report generation

4.94/5 (53 votes)
20 Aug 2008LGPL37 min read 3   29.1K  
ReportExporters is a library for easy exporting of a DataGridView to Excel/PDF/image file types by using Reporting Services report generation.

ample xls-file opened in MS Excel

The ReportExporters uses the Microsoft Report Viewer Redistributable 2005. You can download it from here. Also, if you have installed .NET Framework 3.5, you can try to change the references to the libraries from the Microsoft Report Viewer Redistributable 2008.

Introduction

Some time ago, I was looking for a solution for exporting data from a DataGridView to MS Excel. I tried a well-known method by using the Microsoft.Office.Interop.Excel.Application class, but the application was too slow. So, I tried to find another method.

While working with SQL Server 2005 Reporting Services, I found out that the component ReportViewer can export report data to a native XLS file. When I took a closer look at the Report Definition Language Specification, the idea of creating a library for programmatically generating an RDLC-file occured. The resulting RDLC-file should reproduce the metadata of the DataGridView control (content and layout). This RDLC-file can be loaded to the Microsoft.Reporting.WinForms.LocalReport class by using the method LoadReportDefinition, and the Render method allows to export reports to the selected format. The description of classes and examples for using this library can be found below:

Classes Overview

I have written a few interfaces, a lot of data model classes, and RDLC element wrapper classes. These are the main ones:

IReportExporterProvides common methods for exporting to different formats
WinFormsReportExporterIReportExporter implementation for the Microsoft.Reporting.WinForms library
IReportDataAdapterProvides common methods for gathering meta information about exporting data (type, formatting, grouping etc.); should be used for generation of reports which reproduce the data-container (control)
DataGridViewReportDataAdapterIReportDataAdapter implementation for the System.Windows.Forms.DataGridView control

Main interfaces and classes

The simplest usage of the DataGridViewReportDataAdapter and the WinFormsReportExporter looks like:

C#
DataGridView myDataGridView;
...
//Create DataGridViewReportDataAdapter instance
IReportDataAdapter reportDataAdapter = new DataGridViewReportDataAdapter(myDataGridView);

//Create WinFormsReportExporter instance for reportDataAdapter
IReportExporter winFormsReportExporter = new WinFormsReportExporter(reportDataAdapter);

//Execute method ExportToXls to get Excel file content
MemoryStream xlsFileData = winFormsReportExporter.ExportToXls();
...
//Than xlsFileData can be saved to local disk or etc.

ReportColumns And Styles classes

ReportColumnBase class for ReportDataColumn and ReportHyperlinkColumn.
ReportDataColumnProvides content and view information for the exported column (DataGridViewColumn etc.).
ReportHyperlinkColumnContains a hyperlink for the ReportDataColumn cell. ValueType for this column can be System.String or System.Uri. It doesn't have its own properties, only inherited.

ReportColumn Properties

IndexColumn index in ReportColumnCollection.
NameThe name of the column.
ValueTypeThe data type of the values in the column's cells. For example, it can be initialized from DataGridViewColumn.ValueType.

ReportDataColumn Properties

DataCellViewTypeType of rendering ReportControl for column item cell (TextBox or Image).
DefaultCellStyleStyle for column item cell. Type is ReportStyle.
HeaderCellHyperlinkColumn header cell hyperlink.
HeaderCellViewTypeType of ReportControl for column header cell.
HeaderStyleStyle for column header cell.
HeaderTextText in column header cell.
HyperlinkColumnColumn that contains hyperlink for item cell.
TemplateFormatFormat string which allow to pass an argument like "Image size is {0} Kb".
ValueConverterCustom TypeConverter for converting a value at generating report. For example, there is CustomBooleanConverter which can convert a Boolean value to "+"/"-" or "Yes"/"No"

BaseStyle Properties

BackgroundColorThe color of the background.
BackgroundGradientEndColorThe end color for the background gradient.
BackgroundGradientTypeThe type of the background gradient.
BackgroundImageThe background image.
BorderThe border (includes BorderColor, BorderStyle, BorderWidth).
CalendarThe calendar to use for formatting dates.
ColorThe foreground color.
DirectionIndicates whether text is written left-to-right or right-to-left.
FontThe font (includes FontFamily, FontSize, FontStyle, FontWeight).
FormatThe .NET Framework formatting string.
PaddingThe padding.
TextAlignThe horizontal alignment of text.
TextDecoration The text formatting.
VerticalAlignThe vertical alignment of text.
WritingModeThe writing mode for the text. Indicates whether text is written horizontally or vertically.

ReportStyle Properties

WidthThe current width of the column.
HeightThe column cell height.
NullValueA string displayed in a column cell null value.
WrapSpecifies the content of the cell to wrap in the cell.

Demo Application

In the demo application, I want to show you an example of exporting data of different types (System.String, System.Double, System.Byte[], System.Drawing.Image) with the custom formatting and hyperlinks. The demo uses an API for Google Image Search library of Ilan Assayag in order to get images data for displaying them in a DataGridView.

Here is the result:

DemoApplication

For binding as a datasource, I'm using an array of GImage objects, which can be initialized by an instance of Ilan.Google.API.ImageSearch.SearchResult that contains information returned from Google Image Search for each image.

C#
public class GImage
{
  // Methods
  public GImage(SearchResult _searchResult, string _searchTag);

  // Properties
  public string FullFileName { get; set; }
  public double ImageSize { get; set; }
  public string ImageUrl { get; set; }
  public string SearchTag { get; set; }
  public byte[] ThumbnailData { get; set; }
  public Image ThumbnailImage { get; set; }
  public string ThumbnailUrl { get; set; }
}

Custom ReportDataAdapter

In order to change metadata (columns width, formatting, DataCellViewType, etc.) gathered in DataGridViewReportDataAdapter, or to add grouping of rows, it's necessary to create a custom ReportDataAdapter class (in this demo, it is GImageReportDataAdapter) inherited from the DataGridViewReportDataAdapter class. The DataGridViewReportDataAdapter cannot initialize the ReportDataColumn.DefaultCellStyle.Border, because the DataGridView class does not contain the information about the border of its columns.

C#
public class GImageReportDataAdapter : DataGridViewReportDataAdapterter
{
  private bool useGrouping;
  
  public GImageReportDataAdapter(DataGridView _dataGridView, 
         bool _useGrouping) : base(_dataGridView)
  {
    useGrouping = _useGrouping;
  }

  public override ReportColumnCollection GetColumns()
  {
    ReportColumnCollection toRet = new ReportColumnCollection();

    ReportColumnCollection baseColumns = base.GetColumns();

    ReportDataColumn rcSearchTag = baseColumns[0] as ReportDataColumn;
    ReportDataColumn rcFullFileName = baseColumns[1] as ReportDataColumn;
    ReportDataColumn rcThumbnailUrl = baseColumns[2] as ReportDataColumn;
    ReportDataColumn rcImageSize = baseColumns[3] as ReportDataColumn;
    ReportDataColumn rcImageUrl = baseColumns[4] as ReportDataColumn;
    ReportDataColumn rcThumbnailImage = baseColumns[5] as ReportDataColumn;
    ReportDataColumn rcThumbnailData = baseColumns[6] as ReportDataColumn;

    //Replace ReportDataColumn to ReportHyperlinkColumn
    ReportHyperlinkColumn hyperlinkColumnImageUrl = 
                   ReportHyperlinkColumn.ReplaceDataColumn(rcImageUrl);

    //set ImageUrl column as Hyperlink for ThumbnailUrl Column
    rcThumbnailUrl.HyperlinkColumn = hyperlinkColumnImageUrl;

    // Change ReportControl for ThumbnailData(byte[]) to Image instead TextBox
    CellViewImage databaseCellViewImage = 
       CellViewImage.CreateDatabaseImage(ImageMIMEType.Jpeg);
    databaseCellViewImage.Properties.Sizing = ImageSizing.FitProportional;
    rcThumbnailData.DataCellViewType = databaseCellViewImage;
    
    toRet.Add(rcSearchTag);
    toRet.Add(rcFullFileName);
    toRet.Add(rcThumbnailUrl);
    toRet.Add(rcImageSize);
    // add ReportHyperlinkColumn instead ReportDataColumn
    toRet.Add(hyperlinkColumnImageUrl);
    toRet.Add(rcThumbnailImage);

    //Skip rcThumbnailData because thumbnailDataDataGridViewImageColumn 
    //in DataGridView is invisible
    if (this.dataGridView.Columns[6].Visible)
    {
      toRet.Add(rcThumbnailData);
    }
    
    #region Apply custom formatting for ImageSize ReportDataColumn
    
    rcImageSize.DefaultCellStyle.Format = "N2";
    rcImageSize.TemplateFormat = "{0} Kb";
    
    #endregion

    #region Set custom BackgroundImage for FullFileName ReportDataColumn
    //Get embedded image
    Stream cellBackgroundImageStream = 
      GetResourceStream(Assembly.GetExecutingAssembly(), 
      "cellBackground.png");
    if (cellBackgroundImageStream != null)
    {
      BackgroundImage bgrdImage = new BackgroundImage(
        new EmbeddedImage("cellBackground_png", 
        Image.FromStream(cellBackgroundImageStream)));

      
      rcFullFileName.DefaultCellStyle.BackgroundImage = bgrdImage;
    }
    
    #endregion

    #region Apply custom border to all reportDataColumns instead first(rcSearchTag)

    Border customBorder = new Border();
    customBorder.Color = Color.Red;
    customBorder.Style = System.Web.UI.WebControls.BorderStyle.Dashed;
    customBorder.Width = new System.Web.UI.WebControls.Unit(2, 
                                  System.Web.UI.WebControls.UnitType.Point);
    foreach (ReportColumn rColumn in toRet)
    {
      if ((rColumn is ReportDataColumn) && (rColumn != rcSearchTag))
      {
        ((ReportDataColumn)rColumn).DefaultCellStyle.Border = customBorder;
      }
    }
    
    #endregion

    return toRet;
  }
 ......
}

Grouping

Microsoft Reporting Services allows to group data by criteria. In order to set grouping data, it's necessary to override the GetTableGroups method of the interface IReportDataAdapter. If grouping is not needed, the function should return null.

There is the implementation for GImageReportDataAdapter below:

C#
public override ReportTableGroupList GetTableGroups(ReportColumnCollection columns)
{
  if (!useGrouping)
  {
    return null;
  }
  else
  {
    ReportTableGroupList gImagesGroupList = new ReportTableGroupList();
    {
      ReportTableGroup reportTableGroupBySearchTag = new ReportTableGroup();
      //group by SearchTag
      reportTableGroupBySearchTag.ColumnGrouping.Add(columns[0]);
      //sort by SearchTag(Descending)
      reportTableGroupBySearchTag.ColumnSorting.Add(columns[0],
        ReportExporters.Common.Rdlc.Enums.SortOrder.Descending);

      gImagesGroupList.Add(reportTableGroupBySearchTag);
    }
    return gImagesGroupList;
  }
}

In this demo, I used the ApplyRandomOrderToArray method for applying a random order for the GImage array. You can see the result of row data grouping by using SearchTag; also sort descending by SearchTag as in the screenshot below. The Google search query was "Paris; London; New York" and the checkbox "Use Grouping" was checked.

Grouping rows by SearchTag

Custom Export Settings

Report rendering can be customized by using Device Information Settings. I've written classes inherited from BaseDeviceInfoSettings for each available report rendering type. The PdfDeviceInfoSettings class (ExcelDeviceInfoSettings for exporting to Excel, and ImageDeviceInfoSettings for exporting to image) can be used for getting the DeviceInfo XML element and passing it to the method ExportToPdf(string deviceInfo) of the interface IReportExporter.

C#
PdfDeviceInfoSettings deviceInfo = new PdfDeviceInfoSettings();
//set paper size to A3 (11in × 17in)
deviceInfo.PageHeight = new Unit(11, UnitType.Inch);
deviceInfo.PageWidth = new Unit(17, UnitType.Inch);
string deviceInfoXml = deviceInfo.ToString(); 
MemoryStream pdfFileData = winFormsReportExporter.ExportToPdf(deviceInfoXml);

Several Worksheets in one Excel Workbook

Much to my surprise MS Reporting services allows us to export reports in Excel workbook with several worksheets. It can be designed by placing one by one a few Rectangle controls in the main report and placing in each Rectangle control one Subreport control. In this case we can create an Excel workbook with up to 1000 worksheets. But there is a small problem in this method — on the second and further worksheets the first row is hidden (his height is equal to 1 Pixel).

In the code, in order to use the ability of adding extra worksheets to a workbook it's necessary to put List<IReportDataAdapter> (one instance of IReportDataAdapter per worksheet) in the constructor WinFormsReportExporter.

C#
List<IReportDataAdapter> sameAdapters = new List<IReportDataAdapter>();
for (int aIndex = 0; aIndex < nudSheets.Value; aIndex++)
{
    sameAdapters.Add(gImageReportDataAdapter);
}
winFormsReportExporter = new WinFormsReportExporter(sameAdapters);

//Execute method ExportToXls to get Excel WorkBook with several worksheets
MemoryStream xlsFileData = winFormsReportExporter.ExportToXls();
...
//Than xlsFileData can be saved to local disk or etc.

Several worksheets

How to Export a DataSet

Class DataSetAdapterProvider allows you to create set of IReportDataAdapter for dataset tables. By default it creates objects of class DataViewReportDataAdapter (can be initialized by DataTable.DefaultView). Implementation of the DataViewReportDataAdapter class does not format data(columns). This task is for custom application developers.

DataSetAdapterProvider Methods

CreateAdapterCreate IReportDataAdapter for DataTable (by default DataViewReportDataAdapter). Override to provide custom ReportDataAdapter with formatting.
ReorderAdaptersUsed to order ReportDataAdapter's list(Excel sheets).
GetAdaptersRetreive ReportDataAdapter's list (one ReportDataAdapter per dataset table).
C#
DataSet myDataSet;
....
DataSetAdapterProvider dsaProvider = new DataSetAdapterProvider(myDataSet);

//Retreive list of IReportDataAdapters
List<IReportDataAdapter> datasetAdapters = dsaProvider.GetAdapters();

//Pass list of IReportDataAdapters to WinFormsReportExporter constructor
winFormsReportExporter = new WinFormsReportExporter(datasetAdapters);

//Execute method ExportToXls to get Excel file content
MemoryStream xlsFileData = winFormsReportExporter.ExportToXls();
...
//Than xlsFileData can be saved to local disk or etc.

Displayed in DataGrid exporting DataSet

Other Formats

Anton Ponomarev describes in his article, Adding DOC, RTF, and OOXML Export Formats to the Microsoft Report Viewer Control, adding a custom rendering extension to the standard Microsoft Report Viewer control. He modified the ReportViewer assemblies by using .NET tools. As a result, he got the Microsoft.ReportViewer.WinForms.Modified.dll assembly in which the Report Viewer component is able to generate reports in Microsoft Word formats (DOC, RTF, WordprocessingML, and OOXML) when it works in local mode.

I suppose if references in ReportExporters to Microsoft.ReportViewer.WinForms.dll is changed to Microsoft.ReportViewer.WinForms.Modified.dll, and the IReportExporter interface is extended, then it will be possible to export a DataGridView to DOC, RTF, WordprocessingML, and OOXML formats.

I don't have the Microsoft.ReportViewer.WinForms.Modified.dll yet. I'm going to investigate this problem soon.

Conclusion

With the ReportExporters library, you can:

  • Export a DataGridView/DataSet to native XLS instead of SpeedSheetXML. It is not required that MS Excel be installed.
  • Also export to PDF (uncompressed), BMP, EMF, GIF, JPEG, PNG, and TIFF formats.
  • Specify formatting (font, alignment, number format, border, background etc.) for exporting cells and column headers.
  • Specify the column list to export.
  • Add grouping and sorting for rows.
  • Add hyperlinks to Excel and PDF documents.
  • Add extra worksheets in Excel workbook.
  • Export embedded, external (located in the local system or in the Internet) images.

Points of Interest

It was very interesting and exciting for me to write this library. I hope it will be useful for developers who are looking for a similar solution.

Any suggestions and questions are welcome!

History

  • 2008-07-31: Article created.
  • 2008-08-18: Added features:
    • export to Excel workbook with several worksheets;
    • export System.Data.DataSet to workbook(one worksheet for each of the DataSet tables);

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)