You only need to set contenttype to "application/vnd. MS-excel", indicating that the data is output in Excel mode.
CodeAs follows:
Datatoexcel. aspx:
<% @ Page Language = "C #" autoeventwireup = "true" codefile = "datatoexcel. aspx. cs" inherits = "datatoexcel" %>
datatoexcel
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 ();
}
}
}