ASP.NET에서 Gridview 내용을 Excel로 export하기
1. Gridview에 있는 내용을 Excel로 내 보내기 위해서는 소스 파일(cs)에 System.IO 네임 스페이스를 추가한 후 다음 처리 과정을 거치면 된다.
using System.IO;
이벤트 처리 메소드에서 다음 처리 항목을 입력한다.
string attachment = "attachment; filename=Contacts.xls"; // filename 인 파일 이름을 변수로 지정을 할 수 있다.
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
GridView1.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GridView1);
frm.RenderControl(htw);
//GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
2. 두번째로는 Gridview 를 포함하고 있는 디자인 파일(aspx)에서 페이지 특성을 지정하는 곳에
EnableEventValidation="false"를 지정한다.
<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" %>