Click here to Skip to main content
15,911,139 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,


I have asp.net code to export data to excel. The code that I have is
C#
protected void ExportToExcel() {
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls");
        Response.Charset = "";
        this.EnableViewState = false;

        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

        gvFiles.RenderControl(htw);

        Response.Write(sw.ToString());
        Response.End();
    }


I have data like this in data Table
Numbers
12345,67898
45678,23456
67890,54326,56734
90877,45455,67896

When I export the data table to excel by using the above code the format is changed to by default General after exporting to excel the data is
1,234,456,789
45,678,234,56
6,789,0543,46

How set the format to Text,in Excel while exporting data using Response object.

Help me through C# code.
Posted
Updated 10-Jan-12 20:14pm
v3

We need to apply the cell formatting in the data table using Microsoft.Office.Interop.Excel namespace.
 
Share this answer
 
Comments
sacraj 10-Jan-12 11:22am    
How can we use cell formatting in the data table using Microsoft.Office.Interop.Excel namespace. with this code
protected void ExportToExcel() {
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls");
Response.Charset = "";
this.EnableViewState = false;

System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

gvFiles.RenderControl(htw);

Response.Write(sw.ToString());
Response.End();
}
If you're using Excel 2007 or above, one way is to write the excel file using Open XML. For example, see: Read and write Open XML files (MS Office 2007)[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900