Tuesday, May 31, 2022

Export to excel from sql database SQL Query in ASP.NET C#

 protected void imgexcel_Click(object sender, ImageClickEventArgs e)

    {

          string strQuery = (" EXEC Spu_Get_InvoiceStatus ");

        SqlCommand cmd = new SqlCommand(strQuery);


        DataTable dt = GetData(cmd);


        //dt.Columns.Remove("I_PMU_EntryOn");

        dt.Columns.Remove("yearofBSD");

        dt.Columns.Remove("TP_State_Code");

      

        dt.AcceptChanges();

        GridView GridView1 = new GridView();

        GridView1.AllowPaging = false;

        GridView1.DataSource = dt;

        GridView1.DataBind();

        Response.Clear();

        Response.Buffer = true;

        Response.AddHeader("content-disposition", "attachment;filename=InvoiceStatus.xls");

        Response.Charset = "";

        Response.ContentType = "application/vnd.ms-excel";

        StringWriter sw = new StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(sw);


        for (int i = 0; i < GridView1.Rows.Count; i++)

        {


            //Apply text style to each Row


            GridView1.Rows[i].Attributes.Add("class", "textmode");


        }


        GridView1.RenderControl(hw);

        //style to format numbers to string

        string style = @"<style> .textmode { mso-number-format:\@; } </style>";

        Response.Write(style);

        Response.Output.Write(sw.ToString());

        Response.Flush();

        Response.End();

    }

    private DataTable GetData(SqlCommand cmd)

    {

        DataTable dt = new DataTable();

        String strConnString = Luminious.Connection.Configuration.ConnectionString;

        SqlConnection con = new SqlConnection(strConnString);

        SqlDataAdapter sda = new SqlDataAdapter();

        cmd.CommandType = CommandType.Text;

        cmd.Connection = con;

        try

        {

            con.Open();

            sda.SelectCommand = cmd;

            sda.Fill(dt);

            return dt;

        }


        catch (Exception ex)

        {

            throw ex;

        }


        finally

        {

            con.Close();

            sda.Dispose();

            con.Dispose();

        }


    }

No comments:

Post a Comment