网上最常见的导出代码,这个方法的优点是简单.但是缺点就是不能格式化.
如果datagrid中有linkbutton列,导出程序就会报错
类型“DataGridLinkButton”的控件“DataGrid1__ctl2__ctl0”必须放在具有 runat=server 的窗体标记内。纠正这个错误的方法就是对datagrid进行重新绑定,当然在重新绑定之前最好设置参数,这样查询的时候是LinkButton列,导出的时候是普通列或不生成该列.
我实现的方法,修改导出函数如下:
Session[
"
print
"
]
=
"
1
"
;
SetBind(); // 重新绑定datagrid
Session.Remove( " print " ); // 注意:清理session的部分不能写在DataGrid1_ItemDataBound中
// 因为DataGrid1_ItemDataBound是一行一行绑的.如果写在里面就
// 表示绑定了第一行,等第二行的时候还是会绑定LinkButton.
Response.Clear();
Response.Buffer = true ;
Response.Charset = " GB2312 " ;
Response.AppendHeader( " Content-Disposition " , " attachment;filename= " + HttpUtility.UrlEncode(FileName,Encoding.UTF8).ToString());
Response.ContentEncoding = System.Text.Encoding.GetEncoding( " GB2312 " ); // 设置输出流为简体中文
Response.ContentType = " application/ms-excel " ; // 设置输出文件类型为excel文件。
this .DataGrid1.Page.EnableViewState = false ;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo( " ZH-CN " , true );
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this .DataGrid1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
SetBind(); // 重新绑定datagrid
Session.Remove( " print " ); // 注意:清理session的部分不能写在DataGrid1_ItemDataBound中
// 因为DataGrid1_ItemDataBound是一行一行绑的.如果写在里面就
// 表示绑定了第一行,等第二行的时候还是会绑定LinkButton.
Response.Clear();
Response.Buffer = true ;
Response.Charset = " GB2312 " ;
Response.AppendHeader( " Content-Disposition " , " attachment;filename= " + HttpUtility.UrlEncode(FileName,Encoding.UTF8).ToString());
Response.ContentEncoding = System.Text.Encoding.GetEncoding( " GB2312 " ); // 设置输出流为简体中文
Response.ContentType = " application/ms-excel " ; // 设置输出文件类型为excel文件。
this .DataGrid1.Page.EnableViewState = false ;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo( " ZH-CN " , true );
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this .DataGrid1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
1
private
void
DataGrid1_ItemDataBound(
object
sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
2 {
3 if (Session[ " print " ] != null )
4 {
5 if (Session[ " print " ].ToString() == " 1 " )
6 {
7 e.Item.Cells[ 0 ].Visible = false ;
8 e.Item.Cells[ 1 ].Visible = false ;
9 e.Item.Cells[ 2 ].Visible = false ;
10 e.Item.Cells[ 12 ].Visible = false ;
11 }
12 }
13 }
2 {
3 if (Session[ " print " ] != null )
4 {
5 if (Session[ " print " ].ToString() == " 1 " )
6 {
7 e.Item.Cells[ 0 ].Visible = false ;
8 e.Item.Cells[ 1 ].Visible = false ;
9 e.Item.Cells[ 2 ].Visible = false ;
10 e.Item.Cells[ 12 ].Visible = false ;
11 }
12 }
13 }