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...;)

Wednesday, April 20, 2011

Exproting Data From GridView To Excel File...?

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 DatagridToExcel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        ExportToExcel("report.xls", GridView1);
    }

    private void ExportToExcel(string strFileName, GridView gv)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.xls";
        Response.AddHeader("content-disposition",
        "attachment;filename=" + strFileName);
        Response.Charset = "";
        this.EnableViewState = false;
        System.IO.StringWriter sw = new StringWriter();
        System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
        gv.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {

    }

}

Here you need to include VerifyRenderingInServerForm() Function also...


Importing From Excel File To Datagrid In ASP.NET.....:)

Here In design page I have one grid id as GVExcel.
and G:\\Yash\\WorkInProgress\\TestProject\\website1\\Student.xls path of excel file which has to import.


protected void Page_Load(object sender, EventArgs e)
    {       
        try
        {
            string conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=G:\\Yash\\WorkInProgress\\TestProject\\website1\\Student.xls;Extended Properties=Excel 8.0;";

            DataSet ds = new DataSet();
            OleDbDataAdapter da = new OleDbDataAdapter("select * From [Sheet1$]", conn);
            da.Fill(ds);
            GVExcel.DataSource = ds;
            GVExcel.DataBind();
        }
        catch(Exception ex)
        {
        }
        finally
        {
            // Close connection
            //oledbConn.Close();
        }     
    }

Hope this code is helpful for you.

Thursday, April 14, 2011

Create, Read, write and appending Data to textFile?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ReadWriteAppendTextFile
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteToFile();
            ReadFromFile("G:\\MyTextFile.txt");
            AppendToFile();
        }

        #region Function Used to create/Write text file

        static void WriteToFile()
        {           
            StreamWriter SW;
            SW = File.CreateText("G:\\MyTextFile.txt");
            SW.WriteLine("God is greatest of them all");
            SW.WriteLine("This is second line");
            SW.Close();
            Console.WriteLine("File Created SucacessFully");
        }
        #endregion


        #region Creating Data from text file

        static void ReadFromFile(string filename)
        {
            StreamReader SR;
            string S;
            SR = File.OpenText(filename);
            S = SR.ReadLine();
            while (S != null)
            {
                Console.WriteLine(S);
                S = SR.ReadLine();
            }
            SR.Close();
        }
        #endregion

        #region Function used to append data to text file

        static void AppendToFile()
        {
            StreamWriter SW;
            SW = File.AppendText("G:\\MyTextFile.txt");
            SW.WriteLine("This Line Is Appended");
            SW.Close();
            Console.WriteLine("Text Appended Successfully");
        }
        #endregion
    }
}