0% found this document useful (0 votes)
39 views

Exporting A DataTable To Excel

This article describes a handy function to export a DataTable to Microsoft Excel. The function allows you to choose which columns to export and specify the encoding. It loops through the DataTable, writes the column titles and then each row to the response as comma separated values. The response is given the correct headers and content type so that it downloads as a CSV file that Excel can open as a spreadsheet. The function is lightweight, quick, and allows customizing the exported columns and encoding.

Uploaded by

faizanmuslim
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Exporting A DataTable To Excel

This article describes a handy function to export a DataTable to Microsoft Excel. The function allows you to choose which columns to export and specify the encoding. It loops through the DataTable, writes the column titles and then each row to the response as comma separated values. The response is given the correct headers and content type so that it downloads as a CSV file that Excel can open as a spreadsheet. The function is lightweight, quick, and allows customizing the exported columns and encoding.

Uploaded by

faizanmuslim
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

This article belongs to http://aspguy.wordpress.

com
Written by Aref Karimi
igilu !yahoo.com

Exporting a DataTable to Excel

In many cases Microsoft Ecel can do much for you and reduce your programming efforts. For
eample, if you must provide a printable version of a data collection or you need to provide a report
with grouping, you may send all information to Ecel and let the end-user do it with Ecel. Therefore,
knowing how to eport a data collection (i.e. a ataTable) to Microsoft Ecel can be helpful and
sometimes reliving!

In ASP.NET, you may eport a GridView control to ecel but I do not think it is a good way (ecept in
certain cases) because we mostly do not display the whole columns and rows in a grid (i.e. for
paging reason). Plus, eporting a GridView control needs to re-render the grid into response output
stream and it might be time/resource consuming.

In the rest of this article we will write a handy function to eport a ataTable to Microsoft Ecel. The
features of this function are as follows:

2. Is very quick
. Is very lightweight
4. You may choose which columns to be eported
6. You may specify your desired encoding

Ok let's get started. The method we are going to write is named EportToSpreadsheet and have the
following signature:

public static void ExportToSpreadsheet(DataTable table, string name, string


ColumnList)

The 2st argument is the ataTable object we are going to eport. The nd one is the name of
generated target file and ColumnList is a comma-separated list of columns to be eported. Not
always do we eport all columns. Thus we should be able to choose which columns to be eported.

The file we are going to generate is a Comma Separated Value (.csv) file because Ecel knows this file
and opens it like a spread-sheet. In the other hand, we do not have to create a real .ls file.

Ok, for the implementation part we first convert the ColumnList argument to an IList collection. This
is necessary because we need to find a column name in the list later.

IList<string> collist = new List<string>();


string[] columnstr = ColumnList.ToUpper().Split(',');
foreach (string s in columnstr)
collist.Add(s);

The above code splits the ColumnList argument into a string array and adds each string item to an
IList object. I had to use foreach statement because the code was wri<en in C= . . In C= 4. you
may omit Foreach and use .ToList() etension instead. I mean the above code will get shorter in
this way:
This article belongs to http://aspguy.wordpress.com
Written by Aref Karimi
igilu !yahoo.com

IList<string> collist = ColumnList.ToUpper().Split(',').ToList();

Since we are sending the .CSV file to HttpResponse, we create a new HttpContet instance, and set
the ContentEncoding property. We would better set ContentEncoding since the encoding used in
clients might be different from the response encoding! For eample suppose you have a website
whose response encoding is UTF-A but your clients use Windows-2BC encoding. If you eport the
.CSV file in UTF-A format clients will not show the strings correctly. In this code I have used
Encoding.Default but you may let the the encoding to be chosen as a new argument for
ExportToSpreadsheet method.

context.Response.ContentEncoding = Encoding.Default;
ontext.Response.Clear();

Afterwards, we start to loop over the ataTable.Columns collection to create the titles. For column
titles I have used ataColumn.Caption property (and not ataColumn.ColumnName) since the title is
not necessarily equal to the column name. For instance a column name might be Cust_Title but the
caption should be "Customer's Full Name". I recommend to use typed datasets because setting such
properties are very easy in VS.:

foreach (DataColumn column in table.Columns)


{
if (ColumnList=="" ||
collist.Contains(column.ColumnName.ToUpper()))
context.Response.Write(column.Caption + ";");
}

After creating column titles, we loop over rows and add them to the .csv :

foreach (DataRow row in table.Rows)


{
foreach(DataColumn column in table.Columns)
{
if (ColumnList == "" ||
collist.Contains(column.ColumnName.ToUpper()))
context.Response.Write(row[column].ToString().Replace(";",
string.Empty) + ";");
}
context.Response.Write(Environment.NewLine);
}

At the end, we alter the http header in following way to get the download process started:

context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment;
filename=" + name);
context.Response.End();

That's it.

You might also like