Skip to content

Exporting data from sql database to excel spreadsheet

Zimbini Walaza

Asked Aug 30, 2008, 2:03 AM EDT2 answers
Share
LinkedInX

Could you please modify the code to work for a desktop application.I tried changing it myself,but i do not know what to use to replace the Response keyword

TypeScript
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GridAllRecord.AllowPaging = false;
        bindData();
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType="application/vnd.ms-excel";
        Response.Charset = "";
        this.EnableViewState = false;
        System.IO.StringWriter  oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        GridAllRecord.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
        Response.End();
    }

    SqlConnection con;
    SqlDataAdapter da;
    SqlCommand cmd = new SqlCommand();
    DataSet ds = new DataSet();

    public void bindData()
    {
        con = new SqlConnection("Data Source=MCN101;Initial Catalog=Data; Uid=sa; pwd=");
        cmd.CommandText = "select pg_FirstName,pg_LastName,pg_StudioName, pg_Address, pg_Phone,pg_City, pg_State, pg_Country from tbl_PhotographerProfile";
        cmd.Connection = con;
        da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        con.Open();
        cmd.ExecuteNonQuery();
        GridAllRecord.DataSource = ds;
        GridAllRecord.DataBind();
    }

    public void gridedit_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {
        GridAllRecord.CurrentPageIndex = e.NewPageIndex;
        bindData();
    }
}

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Bechir Bejaoui
    0
    ouuff, they are tones of code that you wrrite my freind

    here is the solution:
    INSERT INTO    OPENROWSET( 'Microsoft.Jet.OLEDB.4.0',
                   'Excel 8.0;Database=D:\Test.xls',                'SELECT Field1, Field2, Field3,Fieldn FROM [Sheet(m)$]')    Field1, Field2, Field3,Fieldn  FROM Table

    you can execute this directly from within SQL SERVER or create a command from within visual studio and exeute it

    I mean make use of the executeNoneQuery method
    0
  • 1 short reply
    • 0
      Thanx a lot Buchir
      0