0

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!!

  • Try to export csv format instead of xlsx format.. http://stackoverflow.com/questions/13563343/simple-way-to-export-datagridview-to-excel – Anant Dabhi Jul 06 '13 at 09:16
  • tip - http://social.msdn.microsoft.com/Forums/vstudio/en-US/08d69589-4052-410f-a85c-c38493c0a664/creatingwriting-to-an-excel-file-with-c – Ron.B.I Jul 06 '13 at 09:31

3 Answers3

0

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

See here.

Community
  • 1
  • 1
Software Engineer
  • 3,906
  • 1
  • 26
  • 35
0

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();
Priya
  • 1,375
  • 8
  • 21
  • 45
  • Do I still need the string writer and html text writer? – user2015043 Jul 06 '13 at 12:39
  • I try to use the Response.TransmitFile(fileName); it give me an error, "Could not find a part of the path ...." because the file is save in client machine, how I can transmit the file? Please help, thanks – user2015043 Jul 06 '13 at 12:47
  • Rather than creating file on Client machine, you can create it on server.Use the path of server.Make sure to give permissions to the folder on server(The folder which you will use to save the file.) once client download the file, you can write the code to delete the file.So that junk files won't be there after usage. – Priya Jul 08 '13 at 06:36
  • There is no need to create file on client's machine.Better way is to create it on your server.You can access it with ease and by using Response.TransmitFile(fileName) , you can send it to client. – Priya Jul 08 '13 at 06:38
0

Use Response.Write instead of Response.Output.Write.

Banana
  • 136
  • 1
  • 1
  • 7