Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export Excel : Avoid stripping the leading zeros

Tags:

c#-4.0

I am Export a data to Excel Sheet in C#.Net. There i am having column which has the data like "00123450098". The data is exported without the first zero's. I want to show the data as it is.

Here is my export excel code.

 string style = @"<style> .text { mso-number-format:\@; } </style> ";
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader(
        "content-disposition", string.Format("attachment; filename={0}", fileName));
    HttpContext.Current.Response.ContentType = "application/ms-excel";
    HtmlForm frm = new HtmlForm();
    ...................
    ...................
     table.RenderControl(htw);
            HttpContext.Current.Response.Write(style);
            //render the htmlwriter into the response
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.End();
like image 927
RobinHood Avatar asked Jul 20 '12 07:07

RobinHood


People also ask

How do I keep leading zeros in Excel when exporting?

Select all columns with leading zeroes and set Column data format to Text. Click OK and then Finish. Keep the default values inside the Import Data dialogue and click OK. Now you can make modifications to the file and save the file as an Excel document or a CSV file.


2 Answers

While exporting to excel, adding \t before the value being inserted will solve the problem. Eg:

string test = "000456";
string insertValueAs = "\t" + test;

The string test would then be considered as a string value and not an integer value. Thus, it would retain the leading zeros.

I have faced the same issue, and above solution worked for me. Hope this post helps!

like image 82
mounisha nandella Avatar answered Oct 10 '22 16:10

mounisha nandella


If exporting to CSV / TSV, put this into each cell containing a textual "number" with leading 0s or (especially) 16+ digits:

="0012345"

..where 0012345 is the number you want to export to that cell.

I wish I could remember where I saw that.

like image 45
Aaron West Avatar answered Oct 10 '22 17:10

Aaron West