views:

68

answers:

4

I use the following code: (returns an excel obviously)

   ControllerContext.HttpContext.Response.ContentType = "application/ms-excel";
   ControllerContext.HttpContext.Response.Write(sw.ToString());
   ControllerContext.HttpContext.Response.End();
   return View();

where sw is a StringWriter in which i create my excel structure(a table). So, sw.ToString() is a table and some tds contains values like 0001234. When i open the excel file i see in those tds 1234, with no zeroes. What must i do to see those zeroes?

A: 

Haven´t tried this myself, but in Excel if you put a ' before the number, it treats it as a string. Maybe it works...

santiiiii
if i do that it will apear '00001234 but isn't there any better soution?
bogus
It might work, but only at the cost of storing the number as a string. I think NickLarsen's answer, while more difficult, leads to better results.
Steven Sudit
@bogus: Leading zeros aren't significant, so Excel drops them. If you want to always display 8 digits, that's a formatting issue, as NickLarsen suggested.
Steven Sudit
@Steven: Excel does in fact know different data *types*, which is something different than formatting. If the cell contains a string data value, it is handled in a different way and leading 0s are not stripped, but the default is number data.
Lucero
@Lucero: I don't think we disagree.
Steven Sudit
@Steven: Perfect if we agree on this, it was meant as complement to your comment. I just wanted to point out that formatting and data types are actually two things in Excel, which may not be clear for all readers here. Leading zero's are only insignificant for numeric data, strings are just strings...
Lucero
@Lucero: Right. We can keep the leading zeros if we don't mind treating the data as strings, but I'd think that we'd want to do math on the numbers. Once we allow them to be parsed as numbers, the insignificant zeros are relegated to a formatting choice.
Steven Sudit
@Steven: Exactly. :)
Lucero
+1  A: 

What is the file format you're generating? Since you're talking of TDs, I assume that you're working with HTML.

Try to generate XMLSS instead. It allows you to specify most formatting and it's just a plain XML file, so that generating it is not so much of a hassle. (You can get the basic structure by saving a document as "XML Spreadsheet 2003" format)

Lucero
That's an interesting idea.
Steven Sudit
A: 

You can add a css style to the TDs:

As a text:

<style type="text/css">
.number-txt { mso-number-format:\@ }
</style>

<td class="number-txt">0001234<td>

As a number:

<style type="text/css">
.number { mso-number-format:0000000 }
</style>

<td class="number">0001234<td>
Paulus E Kurniawan
Hmm, will Excel honor these at any level?
Steven Sudit
A: 

Well, one solution would be to write a &nbsp in every td then the value and it looks great.

tw.RenderBeginTag(HtmlTextWriterTag.Td); tw.Write("  ");
tw.Write(value); tw.RenderEndTag();

bogus