protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml(AppDomain.CurrentDomain.BaseDirectory + "XMLFile1.xml");
GridView1.DataSource = ds;
GridView1.DataBind();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=TaoBaoItems.xls");
Response.Charset = "gb2312";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
EnableViewState = false;
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
解决这个的办法有一个:
public override void VerifyRenderingInServerForm(Control control)
{
}
加上上面这个重写的代码后,就能保存为excel文件了,是不是很爽啊?
那么不这样写可不可以呢?
回答当然也是肯定的:
办法就是:
不要使用gridview这个东东来绑定数据,用大伙比较喜欢的:Repeater控件来绑定程序!
代码还是一样滴:
Code:
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml(AppDomain.CurrentDomain.BaseDirectory + "XMLFile1.xml");
GridView1.DataSource = ds;
GridView1.DataBind();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=TaoBaoItems.xls");
Response.Charset = "gb2312";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
EnableViewState = false;
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
HTML:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table>
<tr><td>姓名</td><td>年龄</td></tr>
</HeaderTemplate>
<ItemTemplate>
<tr><td><%#Eval("name")%></td><td><%#Eval("age")%></td></tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
这样导出成excel报表就没问题了。
其实有时候你会发现,如果你导出来的表格出现了乱码,这就很郁闷了,年龄列的表头名字为:“骞撮緞”,这是个什么编码?
我又不是神仙,我怎么知道,于是又想了个办法,代码如下:
static void Main(string[] args)
{
string sttest = "骞撮緞";
EncodingInfo[] infoList=Encoding.GetEncodings();
foreach (EncodingInfo encode in infoList)
{
byte[] buffer1 = encode.GetEncoding().GetBytes(sttest);
string strBuffer = Encoding.UTF8.GetString(buffer1);
Console.WriteLine("Encoding={0},编码为:{1}", encode.Name.ToString(), strBuffer);
}
}
乖乖啊,乱码一大堆,不过如黑暗中见一丝曙光,有几个是“年龄”,于是挑了一个比较熟悉的编码:“GB18030”,于是将代码改成如下:
protected void Button1_Click(object sender, EventArgs e)
{
Response.AddHeader("content-disposition", "attachment;filename=TaoBaoItems.xls");
//网站编码
Response.Charset = "utf-8";
//输出编码
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB18030");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
Repeater1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
OK,一切搞定了,这个世界终于安静下来了!
从此以后,大伙导出excel就是成事不求人了!