当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET技巧:数据岛出到Excel最为简易的方法

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

2018年04月29日  | 移动技术网IT编程  | 我要评论

北京时间在线校准,无墙网,公务员考试条件

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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网