只需将contenttype 设置为 "application/vnd.ms-excel",表示以excel方式输出.
代码如下:
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();
}
}
}
新闻热点
疑难解答
图片精选