日期:2014-05-19  浏览次数:20862 次

C#導出Excel的代碼不支持分頁功能。請教怎麼修改這段代碼?
导出
protected   void   Button1_Click(object   sender,   EventArgs   e)
        {
                Export( "application/ms-excel ",   "学生成绩报表.xls ");
        }

        private   void   Export(string   FileType,   string   FileName)
        {
                Response.Charset   =   "GB2312 ";
                Response.ContentEncoding   =   System.Text.Encoding.UTF7;
                Response.AppendHeader( "Content-Disposition ",   "attachment;filename= "   +   HttpUtility.UrlEncode(FileName,   Encoding.UTF8).ToString());
                Response.ContentType   =   FileType;
                this.EnableViewState   =   false;
                StringWriter   tw   =   new   StringWriter();
                HtmlTextWriter   hw   =   new   HtmlTextWriter(tw);
                GridView1.RenderControl(hw);
                Response.Write(tw.ToString());
                Response.End();
        }


------解决方案--------------------
public void OuttoExcel()
{
this.DataGrid1.AllowPaging = false;


string sql= "select * from car_usestatus where state= '已入库 ' order by out_time DESC ";
DatabaseConnect c=new DatabaseConnect();
DataSet ds=c.getBinding(sql, "t ");

Response.Clear();
Response.Buffer= true;
Response.ContentType = "application/vnd.ms-Excel ";
Response.Charset = " ";
this.EnableViewState = false;

System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);


DataGrid1.DataSource = ds.Tables[ "t "].DefaultView; //返回DataSet或DataTable
DataGrid1.DataBind();

ClearControls(DataGrid1);

DataGrid1.RenderControl(oHtmlTextWriter);

Response.ContentEncoding = System.Text.Encoding.UTF8;

Response.Write(oStringWriter.ToString());

Response.End();
this.DataGrid1.AllowPaging = true;
}
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i > = 0; i--)
{
ClearControls(control.Controls[i]);
}

if (!(control is TableCell))
{
if (control.GetType().GetProperty( "SelectedItem ") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text = (string)control.GetType().GetProperty( "SelectedItem ").GetValue(control, null);
}
catch
{
}
control.Parent.Controls.Remove(control);
}
else if (control.GetType().GetProperty( "