使用Response导出GridView,下载文件
Response是Asp.net的服务器响应对象,其中可以指定输出的内容,可以用它来导出网页或控件(如GridView)等,也可以用来下载文件(用Response下载的好处是文件在网站中的目录结构不会被暴露)
下面就简要介绍下怎么用Response来将GridView导出成Excel和Word,另外下载mp3
首先是网页后台
Default.aspx.cs
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ExportExcel()
{
Response.Clear();
Response.ContentType = "application/ms-excel";
Guid guid=Guid.NewGuid();
Response.ContentEncoding = Encoding.UTF7;//如果输出的文本有中文必须要用UTF-7,很奇怪用UTF-8都是乱码
.
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(guid.ToString() + ".xls", Encoding.UTF8)/*这里要用UTF-8编码否则文件名是中文就会出现乱码*/);
//StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(Response.Output);
GridView1.RenderControl(hw);
//Response.Write(sw.ToString());
Response.Flush();
Response.End();//一定要在这里结束响应输出流,否则导出的东西里不光有GridView,有网页的所有html元素
}
protected void ExportFile()
{
Response.Clear();
Response.ContentType = "application/mp3";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("歌曲" + "123.mp3", Encoding.UTF8));
FileStream fs = new FileStream(Server.MapPath("~/File/歌曲.mp3"), FileMode.Open);
Response.AppendHeader("Content-Length",fs.Length.ToString());//将文件大小写入Http头,下载文件的时候才会显示进度条
byte[] fb = new byte[fs.Length];
fs.Read(fb, 0, (int)fs.Length);
fs.Close();
Response.OutputStream.Write(fb, 0, fb.Length);//输出文件的时候就用Response的输出流
Response.Flush();
Response.End();
}
protected void ExportWord()
{
Response.Clear();
Response.ContentType = "application/ms-rtf";
Guid guid = Guid.NewGuid();
Response.BufferOutput = true;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(guid.ToString() + ".rtf", Encoding.UTF8));
Response.ContentEncoding = Encoding.UTF7;
HtmlTextWriter hw = new HtmlTextWriter(Response.Output);
GridView1.RenderControl(hw);
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)//这个函数必须重写否则在GridView1.RenderControl(hw);的时候会被告知GridView没有放在具有runat="server"的容器里,说白了就是最外层的form没有被输出到输出流
{
}
protected void Button1_Click(object sender, EventArgs e)
{
ExportExcel();
}
protected void Button2_Click(object sender, EventArgs e)
{
ExportFile();
}
protected void Button3_Click(object sender, EventArgs e)
{
ExportWord();
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ExportExcel()
{
Response.Clear();
Response.ContentType = "application/ms-excel";
Guid guid=Guid.NewGuid();
Response.ContentEncoding = Encoding.UTF7;//如果输出的文本有中文必须要用UTF-7,很奇怪用UTF-8都是乱码
![](https://images.cnblogs.com/dot.gif)
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(guid.ToString() + ".xls", Encoding.UTF8)/*这里要用UTF-8编码否则文件名是中文就会出现乱码*/);
//StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(Response.Output);
GridView1.RenderControl(hw);
//Response.Write(sw.ToString());
Response.Flush();
Response.End();//一定要在这里结束响应输出流,否则导出的东西里不光有GridView,有网页的所有html元素
}
protected void ExportFile()
{
Response.Clear();
Response.ContentType = "application/mp3";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("歌曲" + "123.mp3", Encoding.UTF8));
FileStream fs = new FileStream(Server.MapPath("~/File/歌曲.mp3"), FileMode.Open);
Response.AppendHeader("Content-Length",fs.Length.ToString());//将文件大小写入Http头,下载文件的时候才会显示进度条
byte[] fb = new byte[fs.Length];
fs.Read(fb, 0, (int)fs.Length);
fs.Close();
Response.OutputStream.Write(fb, 0, fb.Length);//输出文件的时候就用Response的输出流
Response.Flush();
Response.End();
}
protected void ExportWord()
{
Response.Clear();
Response.ContentType = "application/ms-rtf";
Guid guid = Guid.NewGuid();
Response.BufferOutput = true;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(guid.ToString() + ".rtf", Encoding.UTF8));
Response.ContentEncoding = Encoding.UTF7;
HtmlTextWriter hw = new HtmlTextWriter(Response.Output);
GridView1.RenderControl(hw);
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)//这个函数必须重写否则在GridView1.RenderControl(hw);的时候会被告知GridView没有放在具有runat="server"的容器里,说白了就是最外层的form没有被输出到输出流
{
}
protected void Button1_Click(object sender, EventArgs e)
{
ExportExcel();
}
protected void Button2_Click(object sender, EventArgs e)
{
ExportFile();
}
protected void Button3_Click(object sender, EventArgs e)
{
ExportWord();
}
}
前台Default.aspx:
<%@ 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></title>
</head>
<body>
<form id="form1" runat="server">
<div style="font-size:10pt;">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataKeyNames="id" DataSourceID="SqlDataSource1"
GridLines="Horizontal" Width="769px">
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<Columns>
<asp:BoundField DataField="id" HeaderText="编号" InsertVisible="False"
ReadOnly="True" SortExpression="id" >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="name" HeaderText="姓名" SortExpression="name" >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="age" HeaderText="年龄" SortExpression="age" >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingRowStyle BackColor="#F7F7F7" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestDBConnectionString %>"
SelectCommand="SELECT t_Student.* FROM t_Student"></asp:SqlDataSource>
</div>
<div>
<asp:Button ID="Button1" runat="server" Text="导出成Excel"
onclick="Button1_Click" />
<asp:Button ID="Button3" runat="server" onclick="Button3_Click"
Text="导出成word" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="下载歌曲" />
</div>
</form>
</body>
</html>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div style="font-size:10pt;">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataKeyNames="id" DataSourceID="SqlDataSource1"
GridLines="Horizontal" Width="769px">
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<Columns>
<asp:BoundField DataField="id" HeaderText="编号" InsertVisible="False"
ReadOnly="True" SortExpression="id" >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="name" HeaderText="姓名" SortExpression="name" >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="age" HeaderText="年龄" SortExpression="age" >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingRowStyle BackColor="#F7F7F7" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestDBConnectionString %>"
SelectCommand="SELECT t_Student.* FROM t_Student"></asp:SqlDataSource>
</div>
<div>
<asp:Button ID="Button1" runat="server" Text="导出成Excel"
onclick="Button1_Click" />
<asp:Button ID="Button3" runat="server" onclick="Button3_Click"
Text="导出成word" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="下载歌曲" />
</div>
</form>
</body>
</html>