ASP.NET技巧:数据岛出到Excel最为简易的方法
只需将contenttype 设置为 "application/vnd.ms-excel",表示以excel方式输出.
代码如下:
datatoexcel.aspx:
<%@ page language="c#" autoeventwireup="true" codefile="datatoexcel.aspx.cs" inherits="datatoexcel" %>
<html xmlns="">
<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();
}
}
}
下一篇: json数据格式常见操作示例