C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Export Data to CSV ( Excel )


Posted Date: 22 Nov 2004    Resource Type: Articles    Category: .NET Framework

Posted By: AbiBaby (Abishek Bellamkonda)       Member Level: Gold
Rating:     Points: 10



Code to export data to CSV file

using System;
using System.Data;
using System.IO;

public class DataTableHelper
{

///
/// Can stream DataTable to Browser, directly, you need to set
///
/// Response.Clear();
/// Response.Buffer= true;
/// Response.ContentType = "application/vnd.ms-excel";
/// Response.AddHeader("Content-Disposition", "inline;filename=Clientes.xls"); Response.Charset = "";
/// this.EnableViewState = false
/// // ACTUAL CODE
/// ProduceCSV(dt, Response.Output, true);
///
public static void ProduceCSV(DataTable dt, System.IO.TextWriter httpStream, bool WriteHeader)
{
if(WriteHeader)
{
string[] arr = new String[dt.Columns.Count];
for(int i = 0; i<dt.Columns.Count; i++)
{
arr[i] = dt.Columns[i].ColumnName;
arr[i] = GetWriteableValue(arr[i]);
}

httpStream.WriteLine(string.Join(",", arr));
}

for(int j = 0; j<dt.Rows.Count; j++)
{
string[] dataArr = new String[dt.Columns.Count];
for(int i = 0; i<dt.Columns.Count; i++)
{
object o = dt.Rows[j][i];
dataArr[i] = GetWriteableValue(o);
}
httpStream.WriteLine(string.Join(",", dataArr));
}
}

#region CSV Producer
public static void ProduceCSV(DataTable dt, System.IO.StreamWriter file, bool WriteHeader)
{
if(WriteHeader)
{
string[] arr = new String[dt.Columns.Count];
for(int i = 0; i<dt.Columns.Count; i++)
{
arr[i] = dt.Columns[i].ColumnName;
arr[i] = GetWriteableValue(arr[i]);
}

file.WriteLine(string.Join(",", arr));
}

for(int j = 0; j<dt.Rows.Count; j++)
{
string[] dataArr = new String[dt.Columns.Count];
for(int i = 0; i<dt.Columns.Count; i++)
{
object o = dt.Rows[j][i];
dataArr[i] = GetWriteableValue(o);
}
file.WriteLine(string.Join(",", dataArr));
}
}

public static string GetWriteableValue(object o)
{
if(o==null || o == Convert.DBNull)
return "";
else if(o.ToString().IndexOf(",")==-1)
return o.ToString();
else
return "\"" + o.ToString() + "\"";

}
#endregion
}




Responses

Author: Paul Maltar    03 Jun 2005Member Level: Bronze   Points : 0
I used the code that you supplied and built the project on my local machine and it worked perfectly.
I then created a form that would generate a query to pull data from my database and again everything worked perfectly.
Next I wanted to have data download when the button was click but in a different window so I called a simple java script to open a new window and download the data and again everything worked prefect.
I have now pushed the entire project live and it errors.
When the button is clicked to download the csv file the new window opens and closes it self without throwing an error or exporting any data. Do you have any idea why this may happen? I can browse to the page that is opening in the popup window and it will again work perfectly but as a popup it fails everytime only on the production server.

Thanks


Author: Cy Surflex     21 Sep 2006Member Level: Bronze   Points : 0
if you change

Response.AddHeader("Content-Disposition", "inline;filename=Clientes.xls"); Response.Charset = "";

to

Response.AddHeader("Content-Disposition", "attachment;filename=Clientes.xls"); Response.Charset = "";

it will force the user to download the file, instead of displaying it embedded in the browser (in IE)



Author: Srini Chavadam    26 Dec 2006Member Level: Bronze   Points : 0
Hi,

The piece of code you have provided here was really useful and I was able to implement the same code to export my report data to excel files.

But, when I click on 'Open' button on File Open Dialog box, it failing to open as it is not found in the default temparary internet folder.

Do you any solution for the same? If so could you please help me out?

Thanks & Regards
Srinivas






Author: Soapy    29 Dec 2007Member Level: Bronze   Points : 0
Here's a complete code example:
http://soapylamp.com/webdevelopment/codeExample6502.html?id=832


Author: Thakar makwana    30 Sep 2008Member Level: Silver   Points : 1
I have to do same thing which u did here....any one have code with example ??

I need it urgent...

Cheers


Author: Narayanan Sukumaran    01 Oct 2008Member Level: Gold   Points : 2
Hi Thakar makwana,
I am not clear, what you need exactly.
Please see the below code for export to excel

exportButton_click:

Response.Clear();
Response.Buffer= true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
DataGrid1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Export  .  Data  .  CSV  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Cloning in .NET
Previous Resource: Convert 'HTML Emails' to 'Text Emails'
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

conference calls

Contact Us    Privacy Policy    Terms Of Use