2009/3/20 記
GridView を Excel にエクスポート
GridView のデータを Excel にエクスポートします。
エクスポートと言っても、GridView の html コード(table タグとその中身全体)を Response.Write で HTTP 応答出力ストリームに書き込んでいるだけですが。
Code | ProductName | ProductID | UnitPrice | Qty | Ext. Price |
1 | Name-1 | PID-1 | 100 | 1 | 100 |
2 | Name-2 | PID-2 | 200 | 2 | 400 |
3 | Name-3 | PID-3 | 300 | 3 | 900 |
4 | Name-4 | PID-4 | 400 | 4 | 1600 |
5 | Name-5 | PID-5 | 500 | 5 | 2500 |
6 | Name-6 | PID-6 | 600 | 6 | 3600 |
7 | Name-7 | PID-7 | 700 | 7 | 4900 |
8 | Name-8 | PID-8 | 800 | 8 | 6400 |
9 | Name-9 | PID-9 | 900 | 9 | 8100 |
10 | Name-10 | PID-10 | 1000 | 10 | 10000 |
コードは以下のとおりです。
<%@ 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>