Tuesday, August 6, 2013

Convet Data into CSV file in Asp.Net




 Source Code

<table class="style1">
        <tr>
            <td>
                &nbsp;
            </td>
        </tr>
        <tr>
            <td>
                <asp:GridView ID="GridView1" runat="server">
                </asp:GridView>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="BtnCSV" runat="server" Text="CSV" OnClick="BtnCSV_Click" />
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
        </tr>
    </table>

C# Code

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

public partial class FrmCSVfile : System.Web.UI.Page
{
    SqlConnection con;
    SqlDataAdapter da;
    DataTable dt;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
            da = new SqlDataAdapter("select * from demo", con);
            dt = new DataTable();
            da.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            ViewState["data"] = dt;
        }

    }
    protected void BtnCSV_Click(object sender, EventArgs e)
    {       
        CreateCSVFile(dt, @"C:\MasterBackup_satyajit\Satyajit Pradhan\xx.csv");
    }


    public void CreateCSVFile(DataTable dt, string strFilePath)
    {     
        dt = (DataTable)ViewState["data"]; 
        StreamWriter sw = new StreamWriter(strFilePath, false);
        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);

        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
    }

}

No comments:

Post a Comment