简体   繁体   中英

Export Datagrid data to Excel C#

I has binding the string Array into Datagrid, then I need to export the data to excel file by auto save the file in client machine. Below is the code i use.

string fileName = "attachment;filename= DetailReport.xlsx";
        Response.Clear();
        Response.AddHeader("content-disposition", fileName);
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.ms-excel";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        grdExcel.RenderControl(htmlWrite);
        Response.Output.Write(stringWrite.ToString());
        Response.Flush();
        Response.End();

I success export the file and save in client machine but the content in the file include all the HTML tag, may I know what wrong to my code? Please Help!!

You need to write the file as binary, either use TransmitFile or BinaryWrite method, just using HtmlTextWriter will not help.

See here .

This might help!

        Response.Buffer = true;
        Response.ContentType = "application/text";
        Response.AppendHeader("Content-Disposition", "attachment; filename=file1.xls");
        Response.TransmitFile(fileName);
        Response.Flush();
        Response.End();

使用Response.Write而不是Response.Output.Write。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM