我先给出部份程序的解释,然后给出整个源代码。
DataSet objDataset = new DataSet();
objConn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionSqlServer"].ToString());
objConn.Open();//在web.config中的配置文件。
SqlDataAdapter objAdapter = new SqlDataAdapter("Select top 10 * from customers where country=@#USA@#",objConn);//这里要改成你的数据库相应的表的选择句语
objAdapter.Fill(objDataset);
DataView oView = new DataView(objDataset.Tables[0]);
dgExcel.DataSource = oView;
dgExcel.DataBind();
objConn.Close();
objConn.Dispose();
objConn = null;
上面部分是从数据库中读出数据显示到DataGrid中去。
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
//关闭 ViewState
EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();//将信息写入字符串
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);//在WEB窗体页上写出一系列连续的HTML特定字符和文本。
//此类提供ASP.NET服务器控件在将HTML内容呈现给客户端时所使用的格式化功能
//参见http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/cpref/html/frlrfsystemwebuihtmltextwriterclasstopic.asp
//获取control的HTML
dgExcel.RenderControl(hw);//将DATAGRID中的内容输出到HtmlTextWriter对象中
// 把HTML写回浏览器
Response.Write(tw.ToString());
Response.End();
全部代码如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
namespace CommonFunction
{
/// <summary>
/// excel 的摘要说明。
/// </summary>
public class excel : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button btnGetExcel;
protected System.Web.UI.WebControls.DataGrid dgExcel;
protected System.Data.SqlClient.SqlConnection objConn;
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
DataSet objDataset = new DataSet();
objConn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionSqlServer"].ToString());
objConn.Open();
SqlDataAdapter objAdapter = new SqlDataAdapter("Select top 10 * from customers where country=@#USA@#",objConn);
objAdapter.Fill(objDataset);
DataView oView = new DataView(objDataset.Tables[0]);
dgExcel.DataSource = oView;
dgExcel.DataBind();
objConn.Close();
objConn.Dispose();
objConn = null;
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btnGetExcel.Click += new System.EventHandler(this.btnGetExcel_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btnGetExcel_Click(object sender, System.EventArgs e)
{
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
//关闭 ViewState
EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();//将信息写入字符串
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);//在WEB窗体页上写出一系列连续的HTML特定字符和文本。
//此类提供ASP.NET服务器控件在将HTML内容呈现给客户端时所使用的格式化功能
//获取control的HTML
dgExcel.RenderControl(hw);//将DATAGRID中的内容输出到HtmlTextWriter对象中
// 把HTML写回浏览器
Response.Write(tw.ToString());
Response.End();
}
}
}
前台的页面:
<%@ Page language="c#" Codebehind="excel.aspx.cs" AutoEventWireup="false" Inherits="CommonFunction.excel" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>excel</title>
<meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="excel" method="post" runat="server">
<TABLE id="Table1" style="Z-INDEX: 102; LEFT: 16px; WIDTH: 288px; POSITION: absolute; TOP: 16px; HEIGHT: 178px"
cellSpacing="1" cellPadding="1" width="288" border="0">
<TR>
<TD>
<asp:datagrid id="dgExcel" runat="server" Font-Names="宋体" Font-Size="9pt" Height="100%" Width="100%"
BorderStyle="None" BorderWidth="1px" BorderColor="#CC9966" BackColor="White" CellPadding="4">
<SelectedItemStyle Font-Bold="True" ForeColor="#663399" BackColor="#FFCC66"></SelectedItemStyle>
<AlternatingItemStyle BackColor="#FFCC99"></AlternatingItemStyle>
<ItemStyle BorderWidth="2px" ForeColor="#330099" BorderStyle="Solid" BorderColor="Black" BackColor="White"></ItemStyle>
<HeaderStyle Font-Bold="True" HorizontalAlign="Center" BorderWidth="2px" ForeColor="#FFFFCC"
BorderStyle="Solid" BorderColor="Black" BackColor="#990000"></HeaderStyle>
</asp:datagrid></TD>
</TR>
<TR>
<TD>
<asp:Button id="btnGetExcel" runat="server" Text="把DataGrid中的保存到Excel"></asp:Button></TD>
</TR>
</TABLE>
</form>
</body>
</HTML>