主要思路,通過GridView來導出文檔。新建一個Aspx頁面,頁面創建GridView控件,後台綁定好數據源。
然後load中直接打印即可導出
前台的GridView
<asp:GridView ID="GridView1" BorderColor="Black" runat="server" AutoGenerateColumns="False" Font-Size="12px" Width="656px" AllowSorting="True" Height="172px"> <Columns> <asp:BoundField DataField="Name" HeaderText="姓名" /> <asp:BoundField DataField="Sex" HeaderText="性別" /> <asp:BoundField DataField="BirthDay" HeaderText="出生日期" /> <asp:BoundField DataField="StudentId" HeaderText="身份證號" /> <asp:BoundField DataField="JieduId" HeaderText="借讀證號" /> <asp:BoundField DataField="Familymemberinfo_Name1" HeaderText="第一監護人姓名" /> </Columns> <HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" /> <RowStyle HorizontalAlign="Center" /> <PagerStyle HorizontalAlign="Center" /> </asp:GridView>
後台:
/// <summary> /// 定義導出Excel的函數 /// </summary> /// <param name="FileType"></param> /// <param name="FileName"></param> private void Export(string FileType, string FileName) { for (int i = 0; i < GridView1.Rows.Count; i++) { //這裡給指定的列編輯格式,將數字輸出為文本,防止數字溢出 GridView1.Rows[i].Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); } Response.Charset = "GB2312"; //Response.ContentEncoding = System.Text.Encoding.UTF8; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); 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(); } /// <summary> /// 此方法必重寫,否則會出錯 /// </summary> /// <param name="control"></param> public override void VerifyRenderingInServerForm(Control control) { }
作者:憤怒的TryCatch
出處:http://www.cnblogs.com/likeli/