C# .NET - I need to export the record which gets display on the gridview

Asked By Pradeep Thangaraja on 25-Sep-12 07:06 AM
if i am exporting the gridview value i am getting an excel file thats is working fine with the give code as shown below


string attachment = "attachment; filename=Data.xls";
      Response.ClearContent();
      Response.AddHeader("content-disposition", attachment);
      Response.ContentType = "application/ms-excel";
      System.IO.StringWriter sw = new System.IO.StringWriter();
      HtmlTextWriter htw = new HtmlTextWriter(sw);
      GV_Dashboard.RenderControl(htw);
      Response.Write(sw.ToString());
      Response.End();

My question is wen the excel i go to the file and select save as at that time in the save type option its shows as "Web Page " thats is not right i need to show the excel format like Excel 97-2003 template

please help me
bhanupratap singh replied to Pradeep Thangaraja on 25-Sep-12 08:20 AM
just paste it into your .cs file and change according to your requirement

This if for Excel and word . choose which is sutaible for you.

protected void ImgExcel_Click(object sender, ImageClickEventArgs e)
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=SupplierList.xls");
            Response.ContentType = "application/vnd.xls";
            System.IO.StringWriter WriteItem = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);


            GrvMfDetails.Columns[9].Visible = false;
            GrvMfDetails.RenderControl(htmlText);
            Response.Write(WriteItem.ToString());
            Response.End();
        }


        protected void ImgWord_Click(object sender, ImageClickEventArgs e)
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=SupplierList.doc");
            Response.ContentType = "application/vnd.word";
            System.IO.StringWriter WriteItem = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
          
            GrvMfDetails.Columns[9].Visible = false;
            GrvMfDetails.RenderControl(htmlText);
            Response.Write(WriteItem.ToString());
            Response.End();
        }

public override void VerifyRenderingInServerForm(Control control)
        {
            // this part is just get data export to excel. 
        }


Thanks
This will help you




Jitendra Faye replied to Pradeep Thangaraja on 26-Sep-12 01:48 AM
Shaw Tee replied to Pradeep Thangaraja on 26-Sep-12 04:39 AM
I export the record from GridView to DataTable first and then export to Excel to save like this

    sheet.InsertDataTable((DataTable)this.dataGrid1.DataSource,true,2,1,-1,-1);
    workbook.SaveToFile("sample.xls", ExcelVersion.Version97to2003);

I use a .NET Excel component.

http://www.e-iceblue.com/Introduce/excel-for-net-introduce.html