protected void btnExport_Click(object sender, EventArgs e)
{
Baosight.EMS.RealManage.BusinessLogic.DefaultImpl.MediumManager aa = new Baosight.EMS.RealManage.BusinessLogic.DefaultImpl.MediumManager();
EnergyT energyName = aa.GetEnergyById(strEnergy);
ToExcelFile(this.Page, "实时数据查询" + "_" + energyName.Name + "_" + strStartTime.Substring(0, 10) + "--" + strEndTime.Substring(0, 10));
}
private void ToExcelFile(System.Web.UI.Control ctl, string tablename)
{
string ExportType = "xls";
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + "" + System.Web.HttpUtility.UrlEncode(tablename, System.Text.Encoding.UTF8) + "." + ExportType);
//Response.AddHeader("Content-Disposition", "inline; filename = \"" + "document_attachment.png" + "\"");
Response.Charset = "UTF8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/ms-" + ExportType;
ctl.Page.EnableViewState = true;
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
grdDisplay.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
就直接输出了
注:
当用GridView导出Execl的时候,会发生只能在执行 Render() 的过程中调用 RegisterForEventValidation的错误提示。
有两种方法可以解决以上问题:
1.修改web.config(不推荐) <pages enableEventValidation ="false" ></pages>
2.直接在导出Execl的页面修改
有两种方法可以解决以上问题:
1.修改web.config(不推荐) <pages enableEventValidation ="false" ></pages>
2.直接在导出Execl的页面修改
<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true"
CodeFile="ExportGridView.aspx.cs" Inherits="ExportGridView" %>
注意泛红部分加入即可。
导入到excel中可能会出现乱码的情况
这时需要替换两处地方
把
Response.Charset = "UTF8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
替换成
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
两种编码都试试应该就能解决。