Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep excel cell format as text with "date like" data

This seems silly, but I haven't been able to get my values in the format of #/#### to write as the literal string rather than becoming formatted as a date within excel.

I'm using ClosedXML to write to excel, and using the following:

// snip
IXLRangeRow tableRow = tableRowRange.Row(1);
tableRow.Cell(1).DataType = XLCellValues.Text;
tableRow.Cell(1).Value = "2/1997";
// snip

Looking at the output excel sheet I get in the cell 2/1/1997 - even though I'm setting the format as text in code, I'm getting it as a "Date" in the excel sheet - I checked this by right clicking the cell, format cell, seeing "date" as the format.

If I change things up to:

// snip
IXLRangeRow tableRow = tableRowRange.Row(1);
tableRow.Cell(1).Value = "2/1997";
tableRow.Cell(1).DataType = XLCellValues.Text;
// snip

I instead get 35462 as my output.

I just want my literal value of 2/1997 to be displayed on the worksheet. Please advise on how to correct.

like image 284
Kritner Avatar asked Aug 25 '15 12:08

Kritner


People also ask

How do I change date to text without losing format?

Copy the dates that are in the cells that you want to convert. Copy the text and paste it into Notepad. Return to Excel and pick the cells into which you wish to paste the dates. Go to Home –> Number and pick the Text format with the cells chosen (from the drop down).

How do I make Excel show the date as text?

Here are the steps to do this: Select all the cells that contain dates that you want to convert to text. Go to Data –> Data Tools –> Text to Column. This would instantly convert the dates into text format.

How do I concatenate a date and keep the format?

Select a blank cell you will output the concatenation result, and enter the formula =CONCATENATE(TEXT(A2, "yyyy-mm-dd")," ", B2) ( A2 is the cell with date you will concatenate, and B2 is another cell you will concatenate) into it, and press the Enter key.


2 Answers

try this

ws.Cell(rowCounter, colCounter).SetValue<string>(Convert.ToString(fieldValue));
like image 157
Alexey Miller Avatar answered Sep 22 '22 01:09

Alexey Miller


Not sure about from ClosedXML, but maybe try Range.NumberFormat (MSDN Link)

For example...

Range("A1").NumberFormat = "@"

Or

Selection.NumberFormat = "#/####"
like image 43
u8it Avatar answered Sep 23 '22 01:09

u8it