Windows Forms Tricks You May Have Missed, Page 2
Print to Excel
The same report viewer control also has a powerful side feature: the ability to generate Excel spreadsheets based on the report. The following sample code shows how to use the report viewer to read data and save it to Excel. It doesn't require that Microsoft Office even be installed:
string mimeType = null;string encoding = null;string fileNameExtension = null;string streams = null;Microsoft.Reporting.WinForms.Warning warnings = null;string deviceInfo = "<DeviceInfo> <SimplePageHeaders>True</SimplePageHeaders> </DeviceInfo>";Microsoft.Reporting.WinForms.LocalReport localReport = new Microsoft.Reporting.WinForms.LocalReport();localReport.ReportPath = @"..\..\Local Report Store Information.rdlc";this.Adventure.EnforceConstraints = false;localReport.DataSources.Add(new Microsoft.Reporting.WinForms. ReportDataSource("Sales", GetData()));byte bytes = reportViewer1.LocalReport.Render("Excel", deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);System.IO.FileStream fileStream = new System.IO.FileStream(@"c:\ExcelExportSample.xls", System.IO.FileMode.Create);fileStream.Write(bytes, 0, bytes.Length);fileStream.Close();
Knowledge Is Power
Hopefully, these tips for working with Windows Forms-based applications aren't run-of-the-mill for you, and they will help you in your Windows Forms development efforts. Here are a few links to additional resources that may interest you:
- Practical Tips for Boosting the Performance of Windows Forms Apps
- Extending Windows Forms with a Custom Validation Component Library
- MSDN ReportViewer
- SQL Server 2005 Reporting Services in Action
The topic of the next column is yet to be determined. If you have something in particular that you would like to see explained here, you could reach me at firstname.lastname@example.org.
About the Author
Mark Strawmyer (MCSD, MCSE, MCDBA) is a senior architect of .NET applications for large and mid-sized organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in architecture, design, and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C# for the second year in a row. You can reach Mark at email@example.com.