Saturday, August 27, 2011

Exporting datatable to excel

private void ExportToExcel(DataTable dtExcel)
    {
        string fileName = "ExportTocsv";

        HttpContext context = HttpContext.Current;
        context.Response.Clear();

        foreach (DataColumn column in toExcel.Columns)
        {
            context.Response.Write(column.ColumnName);
            context.Response.Write("\t");
        }

        context.Response.Write(Environment.NewLine);
        int index = 1;
        foreach (DataRow row in toExcel.Rows)
        {
            row[0] = index;
            for (int i = 0; i < toExcel.Columns.Count; i++)
            {
                string val = row[i].ToString();
                context.Response.Write(val.Trim());
                context.Response.Write("\t");
            }
            context.Response.Write(Environment.NewLine);
            index += 1;
        }

        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
        context.Response.End();
    }

//This will work very efficiently if you have thousands of rows also

Copying data from data table to sql server table using bulk copy

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Xml.Linq;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;//add these references to ur project
using Microsoft.SqlServer.Management.Smo;


    public class ExcelToTable
    {
        #region Bulk Copy

        public void BulkCopy(DataTable dtDataCopy, bool CreateTable, string TableName)
        {
            string conString = ConfigurationManager.ConnectionStrings["ConString"].ToString();
            SqlConnection con = new SqlConnection(conString);
            try
            {
                if (con.State == ConnectionState.Closed)
                    con.Open();
                Server server = new Server(new ServerConnection(con));
                Table tbl = new Table(server.Databases[server.ConnectionContext.DatabaseName], TableName);
                if (CreateTable)
                {
                    if (server.Databases[server.ConnectionContext.DatabaseName].Tables[TableName] != null)
                        server.Databases[server.ConnectionContext.DatabaseName].Tables[TableName].Drop();

                    Column colTemp = new Column();
                    foreach (DataColumn dc in dtDataCopy.Columns)
                    {
                        colTemp = new Column(tbl, dc.ColumnName.ToString());
                        colTemp.DataType = Microsoft.SqlServer.Management.Smo.DataType.VarChar(300);
                        colTemp.Nullable = true;
                        tbl.Columns.Add(colTemp);
                    }
                    tbl.Create();
                }
                else
                {

                    //Delete the from the table or performig other actions
                }
                if (con.State == ConnectionState.Open)
                    con.Close();
                con = new SqlConnection(conString);
                if (con.State == ConnectionState.Closed)
                    con.Open();
                SqlBulkCopy copy = new SqlBulkCopy(con);

                foreach (DataColumn dc in dtDataCopy.Columns)
                {
                    copy.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);
                }
                copy.DestinationTableName = TableName;
                copy.WriteToServer(dtDataCopy);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {

                con.Close();
            }
        }

        #endregion
    }

Wednesday, July 20, 2011

Adding a new column to a table with the same data existing in other column of same data table with different datatype..

  //Data table creation DataTable dt = new DataTable();
for (int i = 0; i < 10; i++)
dt.Columns.Add("SNo", typeof(string));
{
DataRow dr = dt.NewRow();
dr["SNo"] = i.ToString();
}
//Adding new column saying serailNo with datatype as int
dt.Columns.Add("SerailNo", typeof(int), "Convert(SNo ,System.Int32)");
//Now you can see a new column saying serialno with datatype int32

Sunday, July 17, 2011

Adding S.No column to grid

<asp:TemplateField HeaderText="S.No"><ItemTemplate><%
#Container.DataItemIndexIndex + 1 %></ItemTemplate></asp:TemplateColumn>