Saturday, April 30, 2011

Importing Data From Database table to CSV File???

Here I am writing simple come for importing data from database to CSV file :

My table structure is:


Customer Table:

ID    int   Unchecked
Name  nvarchar(50)      Checked
Age   nvarchar(50)      Checked


Code for importing data:


using System;
using System.Collections;
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.Xml.Linq;
using System.IO;


public partial class CSVDataFromDatabase : System.Web.UI.Page
{
    DataTable tblCustomer = new DataTable("Customer");
    DataRow drCustomer;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnExportToCSV_Click(object sender, EventArgs e)
    {
        CreateCustomerTable();
        DataClassesDataContext Db_Context = new DataClassesDataContext();
        IQueryable<Customer> cusData = Db_Context.Customers;

        foreach (Customer cus in cusData)
        {
            tblCustomer = BindCustomerTable(cus.ID, cus.Name, cus.Age);
        }

        writeDataToCsvFile(tblCustomer, "Customer");
    }

    public void CreateCustomerTable()
    {
        DataColumn col_ID = new DataColumn("ID");
        DataColumn col_Name = new DataColumn("Name");
        DataColumn col_Age = new DataColumn("Age");

        tblCustomer.Columns.Add(col_ID);
        tblCustomer.Columns.Add(col_Name);
        tblCustomer.Columns.Add(col_Age);
    }

    public DataTable BindCustomerTable(int Id, string Name, string Age)
    {
        drCustomer = tblCustomer.NewRow();
        drCustomer["ID"] = Id;

        drCustomer["Name"] = Name;
        drCustomer["Age"] = Age;

        tblCustomer.Rows.Add(drCustomer);

        return tblCustomer;
    }


    public void writeDataToCsvFile(DataTable dt, string filename)
    {

        string strFilePath =  "G:\\"+filename+".csv";

        StreamWriter sw = new StreamWriter(strFilePath, true);
        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();

    }
}


Hope you are enjoying...;)

No comments:

Post a Comment