M# Tutorials

Learn to build .NET applications with M#. Our step-by-step tutorials will get you up-to-speed rapidly.
If you already know ASP.NET and C#, you can master M# in a week or two.

Generating Excel & CSV Files

In this lesson we learn how to generate Excel and CSV files in M#. We will use the entity "Product" created in previous lesson ( Reading CSV File) to export data. M# offers a concrete class called ExcelExporter for exporting excel and CSV files. We will see how easy it is in M# to export meaningful data.

ExcelExporter Class

This class encapsulates Excel or CSV export functionality and has two constructors to instantiate the class, implementing a method “Generate”, which returns the formatted data, which is then dispatched in server response to export Excel or CSV file.

Note: M# provides an extension method “Dispatch” on HttpResponse instance, which is used to send contents of different types in server response.

ExcelExporter Output Option

ExcelExporter class provides an enum type ExcelExporter.Output which is used to determine the export format i.e. Excel or CSV

Exporting Data using IEnumerable

The constructor shown below takes only one parameter to define the name of the “CSV or Excel File” being exported.

This constructor is useful when you want to export data from any type of object other than a DataTable. Instantiating ExcelExporter using this constructor will require you to add the specified columns by calling “AddColumn” method on the ExcelExporter instance and then populating the data by calling “AddRow” method, as shown below:

The code demonstrated above creates a new instance of ExcelExporter, creates the columns, populates the data, calls the “Generate” method of “exporter” and finally dispatches the retuned String Object from “Generate” method with the file type and appropriate encoding. The “mode” variable defines the type of output file, which is CSV. In order to output Excel file select “Output.Excelxml” option.

Exporting Data using DataTable

The second constructor requires a pre-populated System.Data.DataTable object. When using this constructor you do not need to define columns and populate rows explicitly as shown in the pictures below