Wednesday, 28 November 2012

Export data from Gridview to Excel in Asp.net

Export data from Gridview to Excel in Asp.net

protected void btnexport_Click(object sender, EventArgs e)
    {
        //first method
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=GridView_to_Excel.xls");   
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        StringWriter StringWriter = new System.IO.StringWriter();
        HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);
        grdview.Columns.RemoveAt(6);
        grdview.RenderControl(HtmlTextWriter);
        Response.Write(StringWriter.ToString());
        Response.End();

      //second method

    ////    dbconnect ob = new dbconnect();
    ////    int colIndex = 1;
    ////    int rowIndex = 1;
    ////    Excel.Application xlApp;
    ////    Excel.Workbook xlWorkBook;
    ////    Excel.Worksheet xlWorkSheet;
    ////    object misValue = System.Reflection.Missing.Value;
    ////    xlApp = new Excel.Application();
    ////    Excel.Range ExelRange;
   
    ////    DataTable dt = new DataTable();
    ////    dt = ob.Gridbind();

    ////    xlApp = new Excel.Application();
    ////    xlWorkBook = xlApp.Workbooks.Add(misValue);
    ////    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

    ////    foreach (DataRow theRow in dt.Rows)
    ////    {
    ////        rowIndex = rowIndex + 1;
    ////        colIndex = 0;
    ////        foreach (DataColumn dc in dt.Columns)
    ////        {
    ////            colIndex = colIndex + 1;
    ////            xlWorkSheet.Cells[rowIndex + 1, colIndex] = theRow[dc.ColumnName];
    ////            xlWorkSheet.Rows.AutoFit();
    ////            xlWorkSheet.Columns.AutoFit();
    ////        }
    ////    }

    ////    xlWorkSheet.get_Range("b2", "e2").Merge(false);

    ////    ExelRange = xlWorkSheet.get_Range("b2", "e2");
    ////    ExelRange.FormulaR1C1 = "Exel Title or Table Name ";

    ////    ExelRange.HorizontalAlignment = 3;
    ////    ExelRange.VerticalAlignment = 3;

    ////    xlApp.Visible = true;
    ////    ObjectRelease(xlWorkSheet);
    ////    ObjectRelease(xlWorkBook);
    ////    ObjectRelease(xlApp);



    ////}

    ////private void ObjectRelease(object objRealease)
    ////{
    ////try
    ////{
    ////    System.Runtime.InteropServices.Marshal.ReleaseComObject(objRealease);
    ////    objRealease = null;
    ////}
    ////catch (Exception ex)
    ////{
    ////    objRealease = null;
      
    ////}
    ////finally
    ////{
    ////    GC.Collect();
    ////}
    }


    public override void VerifyRenderingInServerForm(Control control)
    {

        /* Verifies that the control is rendered */

    }
  

No comments:

Post a Comment