Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear All ,
I am getting many empty column when I export the gridview data to excel. Please help me to remove unnecessary column in exported excel file. Please have a look below code

grdview.AllowPaging = false;
           grdview.PageIndex = 0;
           grdview.Columns[6].Visible = false;
           Bind();

           Response.ClearContent();
           Response.AddHeader("content-disposition", "attachment; filename=StatusOfAgreement.xls");
           Response.ContentType = "application/excel";
           StringWriter sw = new StringWriter();
           HtmlForm fm = new HtmlForm();
           HtmlTextWriter htw = new HtmlTextWriter(sw);
           Controls.Add(fm);
           fm.Controls.Add(Panel2);
           fm.RenderControl(htw);
           Response.Write(sw.ToString());
           Response.End();

           grdview.AllowPaging = true;
           grdview.Columns[6].Visible = true;
Posted

Check below code

C#
private void ExportGridToExcel()  
   {  
       Response.Clear();  
       Response.Buffer = true;  
       Response.ClearContent();  
       Response.ClearHeaders();  
       Response.Charset = "";  
       string FileName ="test.xls";  
       StringWriter strwritter = new StringWriter();  
       HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);        
       Response.Cache.SetCacheability(HttpCacheability.NoCache);  
       Response.ContentType ="application/vnd.ms-excel";    
       Response.AddHeader("Content-Disposition","attachment;filename=StatusOfAgreement.xls");  
       GridView1.GridLines = GridLines.Both;  
       GridView1.HeaderStyle.Font.Bold = true;  
       GridView1.RenderControl(htmltextwrtter);  
       Response.Write(strwritter.ToString());  
       Response.End();      
  
   }
 
Share this answer
 
Comments
Gihan Liyanage 15-Sep-14 6:26am    
Did you got a solution from my support, I can see you have not accepted any answer.If you are ok with this answer plz accept it. Then any user having same problem can identified it has solved the problem..
i suggest using EPPLUS because it is free and you have no problem for browser compatibility...

C#
var dt = GetDataTable(); //the one that you use in the Bind() method
var dataTable = dt.Select(/*..the columns you need..*//);
using (ExcelPackage pck = new ExcelPackage(newFile))
{
  ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Accounts");
  ws.Cells["A1"].LoadFromDataTable(dataTable, true);
  pck.Save();
}



you can download it with nuget.

https://www.nuget.org/packages/EPPlus/
https://epplus.codeplex.com/wikipage?title=FAQ
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900