Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>GridView’den Excel’e Veri Aktarma | www.yazilimcik.com</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<asp:Button ID="btnExcel" runat="server" Text="Tablodakileri Excel’e Aktar"
Font-Bold="True" ForeColor="Red" onclick="btnExcel_Click"
BorderStyle="Double" Height="30px" Width="300px" /> <b>GridView’den Excel’e Veri Aktarma | www.yazilimcik.com</b>
<br /> <br />
<asp:GridView ID="gvTCMBDoviz" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" Height="300px" Width="500px">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</div>
</form>
</body>
</html>
Default.aspx.cs
// GridView’den Excel’e Veri Aktarma | www.yazilimcik.com
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Xml;
// GridView’den Excel’e Veri Aktarma | www.yazilimcik.com
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// TCMB Döviz Kurlari’ndan Olusan Bir GridView Tablosu Olusturalim:
DataSet ds = new DataSet();
ds.ReadXml("http://www.tcmb.gov.tr/kurlar/today.xml");
gvTCMBDoviz.DataSource = ds.Tables[1];
gvTCMBDoviz.DataBind();
}
protected void btnExcel_Click(object sender, EventArgs e)
{
// Olusturdugumuz TCMB Döviz Kurlari Tablosundaki Verileri Excel’e Aktaralim:
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + "_Excel_Dosyasi.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
form1.Controls.Clear();
form1.Controls.Add(gvTCMBDoviz);
form1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
}
// GridView’den Excel’e Veri Aktarma | www.yazilimcik.com