Home » excel » c# – Programmatically set a sheet's format to text before reading the cell contents

c# – Programmatically set a sheet's format to text before reading the cell contents

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a requirement to read the contents of an excel sheet, write to it and allow for editing and re-importing. The problem I am having is that when user enters a number into the cells in the sheet, the numbers are, on the back, considered indexes on the SharedString table, an effect I do not need. What I would like to do is force the cells in the worksheet to be formatted as text before going ahead to read it. I believe that way, I am sure that my numbers will be treated as Strings. How do I accomplish this please?

I would appreciate examples using the OPENXML library to solve this problem please.

How to&Answers:

The only way to be certain that what you retrieve from Excel will be a string is to call Range.Text (which will return the displayed text based on the current format), which can only be retrieved with a single cells.

However if you want to make the format Text, then just call:

Cells.NumberFormat = "@"

As further details to what I was saying above… Changing the format does not alter the .Value of the cell. Values are generally either Strings, Dates, or Doubles depending on their number format and the contents.


EDIT
Due to your last comment, I did some additional research for you. However, this is not tested by me. If this does not help you, I recommend updating your question to show what you’ve tried to help garner more response from the community.

You should be able to utilize the steps listed in this answer(make sure to upvote if it helps you).

The only variation, you should be able to skip creating a NumberingFormat. When you get to the code:
cellFormat.NumberFormatId = nf2decimal.NumberFormatId; instead of the nf2decimal… just use 49. so…
cellFormat.NumberFormatId = 49; 49 should correspond to the predefined numeberFormat of @ according to this source

Answer:

Like this in VBA:

Cells.Select
Selection.NumberFormat = "@"