欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET技巧:数据岛出到Excel最为简易的方法

程序员文章站 2023-10-21 11:48:22
只需将contenttype 设置为 "application/vnd.ms-excel",表示以excel方式输出.代码如下:datatoexcel.aspx:<%...

只需将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();
        }
    }
}