What you want to see on DotNetFunda.com ?
DotNetFunda.Com Logo
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 64521 |  Welcome, Guest!   Register  Login
 Home > Code Snippets > C# > Import Data to CSV File FROM DataTable ...
Lakhangarg

Import Data to CSV File FROM DataTable

 Code Snippet posted by: Lakhangarg | Posted on: 8/30/2009 | Category: C# Codes | Views: 2117 | Status: [Member] [Moderator] | Alert Moderator   


In th First step we will Clear the Response Object and then we'll attach a csv file with the Response Object. that will be popup once we'll write the Data into it and End the Response Object.

After Attaching the file we'll write the column Name into the CSV File. and then iterate for all the Records to write them into the CSV file.

"" is used to protect the Data if the data contain ',' (Comma) .

DataTable dtProducts=GetProductsFromDB();

string attachment = "attachment; filename=products.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/octet-stream";

//Write Column Names
string str = "ProductNo,Product,SKU,ProductType,Price";
HttpContext.Current.Response.Write(str);
HttpContext.Current.Response.Write(Environment.NewLine);
for(int i =0; i
{
string strRowData="";
for(int jColumns=0; jColumns
{
if(strRowData=="")
strRowData='"'+dtProducts.Rows[jColumns].ToString()+'"';
else
{
strRowData=","+'"'+dtProducts.Rows[jColumns].ToString()+'"';
}
}
HttpContext.Current.Response.Write(strRowData);
HttpContext.Current.Response.Write(Environment.NewLine);
strRowData="";
}
HttpContext.Current.Response.End();

Found interesting? Add this to:


>> Write Response - Respond to this post and get points

More codes snippets

About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/23/2013 9:15:34 AM