1 ------.aspx-----
2 <asp:DataGrid id="ItemsGrid"
3 BorderColor="black"
4 BorderWidth="1"
5 CellPadding="3"
6 AutoGenerateColumns="true"
7 runat="server">
8
9 asp:DataGrid>
10
11 <asp:Button ID="btnExcel" runat="server" Text="Excel" OnClick="btnExcelClick" />
1 ------.cs--------------------
2
3 protected void Page_Load(object sender, EventArgs e)
4 {
5 if (!Page.IsPostBack)
6 {
7 this.ItemsGrid.DataSource = this.setCreateData();
8 this.ItemsGrid.DataBind();
9 }
10 }
11
12 ICollection setCreateData()
13 {
14 DataTable dt = new DataTable();
15
16 dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
17 dt.Columns.Add(new DataColumn("File", typeof(String)));
18 dt.Columns.Add(new DataColumn("From", typeof(String)));
19 dt.Columns.Add(new DataColumn("Subject", typeof(String)));
20 dt.Columns.Add(new DataColumn("RegDate", typeof(String)));
21 dt.Columns.Add(new DataColumn("MailSize", typeof(String)));
22
23 DataRow dr;
24 for (int i = 0; i < 10; i++)
25 {
26 dr = dt.NewRow();
27 dr[0] = i;
28 dr[1] = "fileattach - " + i.ToString();
29 dr[2] = "from - " + i.ToString();
30 dr[3] = "subject - " + i.ToString();
31 dr[4] = "RegDate - " + i.ToString();
32 dr[5] = "MailSize - " + i.ToString();
33 dt.Rows.Add(dr);
34 }
35
36 DataView dv = new DataView(dt);
37 return dv;
38 }
39 protected void btnExcelClick(object o, EventArgs e)
40 {
41 StringBuilder sb = new StringBuilder(500);
42 sb.Append("아이디, 파일, 기간(From), 제목, 날짜, 사이즈");
43
44 foreach (DataGridItem item in ItemsGrid.Items)
45 {
46 sb.Append(Environment.NewLine);
47
48 for (int i = 0; i < item.Controls.Count; i++)
49 {
50 sb.Append(((TableCell)item.Controls[i]).Text.Replace(
",", string.Empty)).Append(",");
51 }
52 }
53
54 DateTime dt = DateTime.Now;
55 string sFileName = "FileName" + "_" + dt.Ticks.ToString() + ".csv";
56
57 Response.ContentType = "application/vnd.ms-excel";
58 Response.AddHeader(
"Content-Disposition", "attachment;fileName=" + sFileName);
59 Response.Charset = "euc-kr";
60
61 Response.Clear();
62 Response.Write(sb.ToString());
63 Response.End();
64 }
65 -----
66 --출처는 퍼왔습니다..