DataGrid导出成word或excel

    private  void  ExportDataGrid(string FileType, string FileName)         // 从DataGrid导出
         {
            Response.Charset 
= "GB2312";
            Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("GB2312");
            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);
            DataGrid1.RenderControl(hw);
            Response.Write(tw.ToString());
            Response.End();
//结束,否则会输出下面的内容
        }

private 
void  Button1_Click(object sender, System.EventArgs e)
        
{
            ExportDataGrid(
"application/ms-word""overred.doc");//生成word
        }


        private 
void  Button2_Click(object sender, System.EventArgs e)
        
{
            ExportDataGrid(
"application/ms-excel""overred.xls");//生成excel
        }

你可能感兴趣的:(datagrid)