Sunday, July 18, 2010

CSV generator for asp.net c# without writing file in server...

Last topic (http://martinkabraham.blogspot.com/2010/07/csv-generator-for-aspnet-c.html) we see generating csv by saving that csv file to server folder that  need to set folder permissions (chmod(7,7,7)). Now lets see to generate csv without writing that to server.
Encoding.ASCII.GetBytes(CompleteCsv) will givbe the bye[] for the  Respose object to binary write.
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.IO;
using System.Text;


        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;
       
        Response.AppendHeader("content-disposition", "attachment;filename=00123.csv");
        Response.ContentType = "application/octect-stream";
        Response.BinaryWrite(Encoding.ASCII.GetBytes(CompleteCsv));
        Response.Flush();
        Response.End();

3 comments:

  1. great this is what i needed..thanks

    ReplyDelete
  2. u no need to worry about that this is basics for commas and Quotation u can ask directly
    just add them inside "" (double quotes) i am writing myown article not from other pages.

    ReplyDelete