问题:在GridView导出到Excel时系统报错。错误内容如下:只能在执行 Render() 的过程中调用 RegisterForEventValidation;
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.InvalidOperationException: 只能在执行 Render() 的过程中调用 RegisterForEventValidation;源错误: 行 74: DataBound();
行 75:
行 76: gvToExcel.RenderControl( htw );
行 77: Response.Write( sw.ToString() );
行 78: Response.End();原因已找到,是因为有asp:CheckBox的关系。但CheckBox是有用的。因为需要部分记录导出,也就是说一页有10条记录,我选中其中的5条,然后只要导出这5条就行。这个问题怎么解决?谢谢先。在线等。
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.InvalidOperationException: 只能在执行 Render() 的过程中调用 RegisterForEventValidation;源错误: 行 74: DataBound();
行 75:
行 76: gvToExcel.RenderControl( htw );
行 77: Response.Write( sw.ToString() );
行 78: Response.End();原因已找到,是因为有asp:CheckBox的关系。但CheckBox是有用的。因为需要部分记录导出,也就是说一页有10条记录,我选中其中的5条,然后只要导出这5条就行。这个问题怎么解决?谢谢先。在线等。
解决方案 »
- 全局异常
- asp向aspx不同域名之间传值 问题
- 用httpfilecollection实现多文件上传时,为什么httpfilecollection.Count一直为0?
- ASP.NET写的一个COM组建现在要给ASP调用服务器上面只有.NET框架,请问怎么调出.NET命令窗口,谢谢
- 如何得知资料库内, 最近新增的十笔资料表?
- .net2008水晶报表显示问题
- 高分请教....有空进来聊聊吧....
- objectdatasource 数据源选不中方法
- 如何用验证控件验证一个网址格式是否合法?
- 为何到服务器就出错!? web.config的问题.
- Button按钮的Click事件触发不了???
- [求助] 为什么GridView的HeaderStyle的Font-Bold为false,但头文本的文字还是粗体?
根据这个原理。你可以自己构建代码。
自己构建就随便看你自己怎么判断条件了
设置好HTTP头。输出去就OK
直接用dataset
写好你要的datatable,要什么样的想办法,循环也好,判断也好,去取得想要的数据集后
我写的不好,用以前的东西给你做个参考
protected void btnExcel_Click(object sender, EventArgs e)
{
DateTime dtNow = DateTime.Now;
string urlPath = HttpContext.Current.Request.ApplicationPath + "/upload/regulation/";
string physicPath = HttpContext.Current.Server.MapPath(urlPath);
//用时间做唯一
string fileName = Convert.ToString(dtNow.Year) + Convert.ToString(dtNow.Month) + Convert.ToString(dtNow.Day) + Convert.ToString(dtNow.Hour);
fileName += Convert.ToString(dtNow.Minute) + Convert.ToString(dtNow.Second) + Convert.ToString(dtNow.Millisecond) + ".xls"; ConvertDatasetToExcel(physicPath + fileName); HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.WriteFile(physicPath + fileName);
string httpHeader = "attachment;filename=UserDiggInfo.xls";
response.AppendHeader("Content-Disposition", httpHeader);
response.Flush();
}
//转为EXCRL
public void ConvertDatasetToExcel(string strFilePath)
{
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";Extended Properties=Excel 8.0;"; OleDbConnection objConn = new OleDbConnection(connString);
OleDbCommand objCmd = new OleDbCommand();
objConn.Open();
objCmd.Connection = objConn;
string strSql = string.Empty;
if (gvUserDiggInfo.Columns.Count != 0)
{
objCmd.CommandText = "CREATE TABLE booktabel(书名 varchar(100),作者 varchar(100),评分 float,评分日期 varchar(100))";
objCmd.ExecuteNonQuery(); DataTable dt = new DataTable();
dt = UserResDiggInfo();
foreach (DataRow row in dt.Rows)
{
strSql = string.Format("INSERT INTO 资源得分情况统计(书名,作者,评分,评分日期) VALUES('{0}','{1}','{2}','{3}') ", row["Title"].ToString(), row["Creator"].ToString(), row["DiggLevel"].ToString(), row["CreateTime"].ToString());
objCmd.CommandText = strSql;
objCmd.ExecuteNonQuery();
}
}
objConn.Close();
}我是抛砖引玉 ,但别给我砖,我要分,记得多给点分。
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Charset = "UTF-8";
Response.ContentType = "application/vnd.ms-excel";
Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
Response.Write("\r\n");
Response.Write("<head>\r\n");
Response.Write("<meta http-equiv=Content-Type content='text/html; charset=utf-8' />\r\n");
Response.Write("</head>\r\n");
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridViewListingHidden.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.Flush();
Response.Close();
Response.End();
{
foreach (DataColumn col in dt.Columns)
{
foreach (DataControlField dcf in gv.Columns)
{
if (dcf is BoundField)
{
BoundField bf = dcf as BoundField;
if (bf != null)
{
if (col.ColumnName.ToLower() == bf.DataField.ToLower())
{
col.ColumnName = bf.HeaderText;
}
}
}
}
}
} #region 导出至Excel功能
/// <summary>
/// 将datatable中的数据导出到指定的excel文件中
/// </summary>
/// <param name="page">web页面对象</param>
/// <param name="tab">包含被导出数据的datatable对象</param>
/// <param name="filename">excel文件的名称</param>
private void export(Page page, DataTable tab, string filename)
{
HttpResponse httpresponse = Page.Response;
RenameDataTableColumns(ref tab);
DataGrid datagrid = new DataGrid();
datagrid.DataSource = tab.DefaultView;
datagrid.AllowPaging = false;
datagrid.HeaderStyle.Font.Bold = true;
datagrid.DataBind();
httpresponse.AppendHeader("content-disposition", "attachment;filename=" + filename); //filename="*.xls";
httpresponse.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
httpresponse.ContentType = "application/ms-excel";
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
datagrid.RenderControl(hw); string filepath = Page.Server.MapPath("..") + "\\dep1Sheet\\" + filename;
StreamWriter sw = System.IO.File.CreateText(filepath);
sw.Write(tw.ToString());
sw.Close(); hw.Close();
tw.Close(); downfile(httpresponse, filename, filepath);
GC.Collect();
httpresponse.End();
} private bool downfile(HttpResponse response, string filename, string fullpath)
{
try
{
response.ContentType = "application/octet-stream"; response.AppendHeader("content-disposition", "attachment;filename=" + filename);
FileStream fs = System.IO.File.OpenRead(fullpath);
long flen = fs.Length;
int size = 102400;//每100k同时下载数据
byte[] readdata = new byte[size];//指定缓冲区的大小
if (size > flen) size = Convert.ToInt32(flen);
long fpos = 0;
bool isend = false;
while (!isend)
{
if ((fpos + size) > flen)
{
size = Convert.ToInt32(flen - fpos);
readdata = new byte[size];
isend = true;
}
fs.Read(readdata, 0, size);//读入一个压缩块
Response.BinaryWrite(readdata);
fpos += size;
}
fs.Close();
System.IO.File.Delete(fullpath);
return true;
}
catch
{
return false;
}
}
#endregion
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "gb2312";
Response.ContentType = "application/vnd.xls";
Response.ContentEncoding = System.Text.Encoding.UTF8; System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.AllowPaging = false;//导出前先取消分页,以便能将所有数据导出。
GridView1.DataBind();//再重新绑定一次数据
int m = GridView1.Columns.Count;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridView1.Rows[i].Cells[m - 1].Visible = false;
GridView1.Rows[i].Cells[m - 1].Enabled = false; } GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End(); GridView1.AllowPaging = true;//导出后先取消分页,以便能将所有数据导出。
GridView1.DataBind();//再重新绑定一次数据
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
UserInfo user = (UserInfo)e.Row.DataItem;
account += user.Account;
LinkButton link = (LinkButton)e.Row.FindControl("LinkButton1");
link.Attributes.Add("onclick", "return confirm('您真的要更新吗?')");
}
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[3].Text = "总计:";
e.Row.Cells[4].Text=account.ToString("#.00");
}
public override void VerifyRenderingInServerForm(Control control)
{}
Response.BufferOutput = true;
//设定输出的字符集
Response.Charset = "GB2312";
//假定导出的文件名为FileName.xls
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//设置导出文件的格式
Response.ContentType = "application/ms-excel";
//关闭ViewState
this.GridView1.EnableViewState = false;
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("ZH-CN", true);
System.IO.StringWriter stringWriter = new System.IO.StringWriter(cultureInfo);
System.Web.UI.HtmlTextWriter textWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
this.GridView1.RenderControl(textWriter);
//把HTML写回浏览器
Response.Write(stringWriter.ToString());
Response.End();
public static List GetUserList()
{
//string conString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection conn = new SqlConnection(conString);
string sql="select top 10 * from UserInfo where id not in(select top 2 id from UserInfo)";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
List userList = new List();
while (sdr.Read())
{
UserInfo user = new UserInfo();
user.Id = (int)sdr["Id"];
user.Uid = (string)sdr["Uid"];
user.Name = (string)sdr["Name"];
user.Sex = sdr["Sex"].ToString();
user.Account = Convert.ToDouble(sdr["Account"]);
userList.Add(user);
}
return userList;
}