You only need to set ContentType to "application/vnd. ms-excel", indicating that the data is output in Excel mode.
The Code is as follows:
DataToExcel. aspx:
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "DataToExcel. aspx. cs" Inherits = "DataToExcel" %>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> DataToExcel </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Asp: GridView ID = "GridView1" runat = "server">
</Asp: GridView>
</Form>
</Body>
</Html> DataToExcel. aspx. cs
Using System;
Using System. Data;
Using System. Configuration;
Using System. Collections;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Data. SqlClient;
Public partial class DataToExcel: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
If (! This. IsPostBack)
{
This. Response. ContentType = "application/vnd. ms-excel ";
String ConnStr = "server = localhost; uid = sa; pwd =; database = northwind ";
SqlConnection Conn = new SqlConnection (ConnStr );
Conn. Open ();
String sqlcmd = "select lastname, firstname, title, address, city from employees ";
SqlCommand cmd = new SqlCommand (sqlcmd, Conn );
SqlDataAdapter adapter = new SqlDataAdapter (cmd );
DataSet ds = new DataSet ();
Adapter. Fill (ds );
This. GridView1.DataSource = ds. Tables [0]. DefaultView;
This. GridView1.DataBind ();
}
}
}