The term csv stands for Comma Seperated values, means each value is seperated by simply a comma.
eg:martin,sobin,alex
The importance of csv is that it can open in excel,Open-office etc. so if we want to export some db data to excel .. the coder can export that to csv so the user can best fit that on Excel or Open-office
This code will help you to generate csv from a dynamically created datable....
This example pull download window to download csv file and save that to local machine.
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.IO;
// csv Generator...Martin
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("SlNo",typeof(string)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
DataRow dr;
for (int i = 0; i < 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + i.ToString();
dt.Rows.Add(dr);
}
string csvdata="";
int appflg = 0;
foreach (DataColumn dc in dt.Columns)
{
if (appflg == 1)
{
csvdata = csvdata + ",";
}
csvdata =csvdata+dc.ColumnName;
appflg = 1;
}
csvdata = csvdata + "\r\n";
string csvdata_row="";
foreach (DataRow drw in dt.Rows)
{
csvdata_row = csvdata_row + drw[0] + "," + drw[1];
csvdata_row = csvdata_row + "\r\n";
}
string CompleteCsv = csvdata + csvdata_row;
StreamWriter sw = new StreamWriter(Server.MapPath(Request.ApplicationPath)+"\\mycsv.csv");
sw.Write(CompleteCsv);
sw.Close();
FileStream fd = new FileStream(Server.MapPath(Request.ApplicationPath) + "\\mycsv.csv",FileMode.Open);
byte[] data=new byte[(int)fd.Length];
fd.Read(data, 0, (int)fd.Length);
fd.Flush();
fd.Close();
Response.AppendHeader("content-disposition", "attachment;filename=00123.csv");
Response.ContentType = "application/octect-stream";
Response.BinaryWrite(data);
Response.Flush();
Response.End();
good post.. was useful...Waiting for a post on how to directly download excel.
ReplyDeletecan we directly download file without writing in the server?
ReplyDeleteok i wil look forward on this.. You can expect this soon..
ReplyDeleteThank u BABA..
:)
http://martinkabraham.blogspot.com/2010/07/csv-generator-for-aspnet-c-without.html
ReplyDeleteRead this ... Me developed that looking forward on u..
Thank u