在项目中建Default.aspx窗体。
html:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>利用Word打印员工报表</title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align: center">
<table border="1" bordercolor="#bed0cd" cellpadding="0" cellspacing="0">
<tr>
<td style="font-weight: bold; font-size: 11pt; text-align: center">
利用Word打印员工报表</td>
</tr>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4" Font-Size="11pt" ForeColor="Black"
GridLines="Vertical">
<FooterStyle BackColor="#CCCC99" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<EditRowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:GridView>
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Button ID="Button1" runat="server" Font-Size="9pt" OnClick="Button1_Click" Text="输出Word报表" style="border-left-color: #3333ff; border-bottom-color: #3333ff; border-top-style: inset; border-top-color: #3333ff; border-right-style: inset; border-left-style: inset; border-right-color: #3333ff; border-bottom-style: inset"/></td>
</tr>
</table>
</div>
</form>
</body>
</html>
CS:
using System;
using System.Data;
using System.Configuration;
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;
using System.IO;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection("Data Source=in-zyz;Database=db_14;Uid=sa;Pwd=123");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Export("application/ms-word", "员工报表.doc");
}
private void Export(string FileType, string FileName)
{
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
private void bind()
{
SqlDataAdapter myda = new SqlDataAdapter("select * from tb_Employee", sqlcon);
DataSet myds = new DataSet();
sqlcon.Open();
myda.Fill(myds);
sqlcon.Close();
GridView1.DataSource = myds;
GridView1.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
}