网站导航网学 原创论文 原创专题 网站设计 最新系统 原创论文 论文降重 发表论文 论文发表 UI设计定制 论文答辩PPT格式排版 期刊发表 论文专题
返回网学首页
网学原创论文
最新论文 推荐专题 热门论文 论文专题
当前位置: 网学 > 设计资源 > .Net编程 > 正文

利用GridView导出数据库中内容到Excel文件

论文降重修改服务、格式排版等 获取论文 论文降重及排版 论文发表 相关服务

下面我将做一个简单的示例,数据库使用SQL自带的数据库Northwind,完整示例代码如下:(以下代码可直接复制运行测试),希望能对你有所帮助!

在前台页新建一个GridView控件,和一个Button控件,示例代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs" Inherits="Default7" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/uploadfile/201101/20/B0171421531.gif" />using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class Default7 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindData();
        }

    }


    private void BindData()
    {
        string ConnectionString = @"Server=(local);database=Northwind;uid=sa;pwd=123456;";
        string query = "SELECT * FROM Orders";
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds, "Orders");
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }


    public override void VerifyRenderingInServerForm(Control control)
    {
        // Confirms that an HtmlForm control is rendered for
    }


    protected void BtnExport_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=Orders.xls");
        Response.Charset = "gb2312";
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        GridView1.AllowPaging = false;
        BindData();
        GridView1.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());
        Response.End();
        GridView1.AllowPaging = true;
        BindData();
    }

}

  • 下一篇资讯: RegeX使用教程
  • 设为首页 | 加入收藏 | 网学首页 | 原创论文 | 计算机原创
    版权所有 网学网 [Myeducs.cn] 您电脑的分辨率是 像素
    Copyright 2008-2020 myeducs.Cn www.myeducs.Cn All Rights Reserved 湘ICP备09003080号 常年法律顾问:王律师