页面设计代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title> 数据导出 </title>
</head>
<body>
<form id="form1" runat="server" >
<asp:GridView runat="server" ID="GridView1" BackColor="yellow" BorderStyle="Solid" >
</asp:GridView>
<asp:Button runat="server" ID="Button1" Text="导 出" OnClick="Button1_Click1"/>
</form>
</body>
</html>
Web.config中数据库配置代码如下:
<?xml version="1.0" encoding="utf-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="constr" connectionString="server = . ; database = Rollcall ; user id = sa ; pwd = sa ;"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
页面后台程序代码如下:
using System;
using System.Activities.Statements;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Diagnostics;
using System.Collections;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.Security;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//页面加载的时候调用数据绑定的方法
DataBind();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
//或者 Confirms that an HtmlForm control is rendered for
}
//数据绑定的方法
private void DataBind()
{
string str = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(str);
SqlCommand sqlcom = new SqlCommand();
sqlcom.Connection = sqlcon;
sqlcom.CommandType = CommandType.StoredProcedure;
sqlcom.CommandText = "proc_selectinfo";
sqlcon.Open();
SqlDataAdapter sqlsda = new SqlDataAdapter(sqlcom);
DataSet ds = new DataSet();
sqlsda.Fill(ds, "数据信息");
GridView1.DataSource = ds;
GridView1.DataBind();
}
public static void ExportToExcel(string Filename, GridView gridView, Page page)
{
page.Response.Clear();
//防止中文内容为乱码
page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
page.Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(Filename + DateTime.Now.ToShortDateString() , System.Text.Encoding.UTF8) + ".xls\"");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gridView.RenderControl(htw);
page.Response.Write(sw.ToString());
page.Response.End();
}
//点击数据导出到 Excel 控件的按钮事件
protected void Button1_Click1(object sender, EventArgs e)
{
//ToExcel(GridView1);
ExportToExcel("DDDDD", this.GridView1, this.Page);
}
}