WebSurfer's Home

""

GridView を Excel にエクスポート

GridView のデータを Excel にエクスポートします。 エクスポートと言っても、GridView の html コード(table タグとその中身全体)を Response.Write で HTTP 応答出力ストリームに書き込んでいるだけですが。


CodeProductNameProductIDUnitPriceQtyExt. Price
1Name-1PID-11001100
2Name-2PID-22002400
3Name-3PID-33003900
4Name-4PID-440041600
5Name-5PID-550052500
6Name-6PID-660063600
7Name-7PID-770074900
8Name-8PID-880086400
9Name-9PID-990098100
10Name-10PID-1010001010000

コードは以下のとおりです。

<%@ Page Language="C#" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.IO" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected DataTable CreateDataTable() { DataTable dt = new DataTable(); DataRow dr; dt.Columns.Add(new DataColumn("Code", typeof(Int32))); dt.Columns.Add(new DataColumn("ProductName", typeof(String))); dt.Columns.Add(new DataColumn("ProductID", typeof(String))); dt.Columns.Add(new DataColumn("UnitPrice", typeof(Decimal))); dt.Columns.Add(new DataColumn("Qty", typeof(Int32))); dt.Columns.Add(new DataColumn("Ext. Price", typeof(Decimal))); for (int i = 0; i < 10; i++) { dr = dt.NewRow(); dr["Code"] = i + 1; dr["ProductName"] = String.Format("Name-{0}", i + 1); dr["ProductID"] = String.Format("PID-{0}", i + 1); dr["UnitPrice"] = 100 * (i + 1); dr["Qty"] = i + 1; dr["Ext. Price"] = 100 * (i + 1) * (i + 1); dt.Rows.Add(dr); } return dt; } void Page_Load(Object sender, EventArgs e) { GridView1.DataSource = CreateDataTable(); GridView1.DataBind(); } protected void Button1_Click(object sender, EventArgs e) { StringWriter stringWriter = new StringWriter(); HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter); HtmlForm form = new HtmlForm(); Response.ContentType = "application/vnd.ms-excel"; Response.AppendHeader("content-disposition", "attachment;filename=file.xls"); Page.Controls.Add(form); form.Controls.Add(GridView1); form.RenderControl(htmlTextWriter); string text = stringWriter.ToString(); text = text.Remove(0, text.IndexOf("<table")); text = text.Remove(text.IndexOf("</table>") + 8); Response.Write(text); Response.End(); } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" > </asp:GridView> <asp:Button ID="Button1" runat="server" Text="Download to Excel File" onclick="Button1_Click" /> </div> </form> </body> </html>