简体   繁体   English

将Datagrid数据导出到Excel C#

[英]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. 我已经将字符串Array绑定到Datagrid中,然后需要通过自动将文件保存在客户端计算机中将数据导出到excel文件。 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? 我成功导出了文件并将其保存在客户端计算机中,但是文件中的内容包括所有HTML标记,请问我的代码有什么问题吗? Please Help!! 请帮忙!!

You need to write the file as binary, either use TransmitFile or BinaryWrite method, just using HtmlTextWriter will not help. 您需要使用TransmitFileBinaryWrite方法将文件编写为二进制文件,仅使用HtmlTextWriter将无济于事。

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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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