protected void HtmlWriteGV(System.Web.UI.Control gv)
{
//方法一,此方法需要添加下面的 public override void VerifyRenderingInServerForm(Control control) 方法,另外前台页面需添加<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ZCNewStatistics.aspx.cs" Inherits="uiniRMS.Admin.ZCNewStatistics" EnableEventValidation = "false" %>
//gv.Page.EnableViewState = false;
//Response.Clear();
//Response.AddHeader("content-disposition",
//"attachment;filename=FileName.xls");
//Response.ContentType = "application/vnd.xls";
//System.IO.StringWriter stringWrite = new System.IO.StringWriter();
//System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
//gv.RenderControl(htmlWrite);
//Response.Write(stringWrite.ToString());
//Response.End();
//方法二
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
Page page = new Page();
HtmlForm form = new HtmlForm();
gv.EnableViewState = false;
// Deshabilitar la validación de eventos, sólo asp.net 2
page.EnableEventValidation = false;
// Realiza las inicializaciones de la instancia de la clase Page que requieran los diseñadores RAD.
page.DesignerInitialize();
page.Controls.Add(form);
form.Controls.Add(gv);
page.RenderControl(htw);
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(data+"统计",System.Text.Encoding.UTF8) + ".xls");
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.Default;
Response.Write(sb.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
-------解
问题描述:开发的系统需要将DataGrdiView的数据导出Excel,首先用的是借助 microsoft.Office.Interop.Excel 来做,这种方法生成的Excel根本不是Excel,只不过扩展名是xls而已,所以打开的时候会提示“您尝试打开的文件**.xls的格式与文件扩展名指定的格式不一致”这是Excel的安全问题,暂时解决办法如下,取消Exce的安全检测。
长久对策:学习利用NPOI来实现Excel的导出,待成功后再与大家分享。
1、开始 -> 运行 -> 输入regedit -> 确定
2、找到注册表子项
HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\Security
3、在右侧空白处点击鼠标右键,选择“新建 -> DWORD值(D)”,输入"ExtensionHardening"点击确定。
4、用鼠标右键点击ExtensionHardening,然后单击“修改(M)”,在数值数据中填写"0"即可确定。
5、关闭注册表编辑器,再次打开xls文件看看是不是提示是不是不见了?
拓展:ExtensionHardening设置的值的数据设置:
0:不检查文件扩展名和文件类型并绕过该函数的警告消息。
1:检查文件扩展名和文件类型。如果它们不匹配会显示警告消息。
2:检查文件扩展名和文件类型。如果它们不匹配不要打开该文件