Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set data type like number, text and date in excel column using Microsoft.Office.Interop.Excel in c#

I am trying to set the data type to an excel column in C#, in this case the data types number, text and date.

How does one set a format to an entire excel column?

like image 788
Jack1987 Avatar asked Dec 11 '12 20:12

Jack1987


People also ask

How do I format a column in Excel in C#?

You just have to change the format of that column or cell to text. '//Format to text ExcelWorksheet. Columns[1]. NumberFormat = "@";' if you are still having trouble let me know.

How do I change the datatype of a column in Excel?

Select the field (the column) that you want to change. On the Fields tab, in the Properties group, click the arrow in the drop-down list next to Data Type, and then select a data type. Save your changes.


Video Answer


1 Answers

To set a range to text:

xlYourRange.NumberFormat = "@";

You can also prefix a value you put in a cell with an apostrophe for it to format it as text:

xlYourRange.Value = "'0123456";

To set a range to number

xlYourRange.NumberFormat = "0";

Obviously if you want to set the format for the entire column then your range will be the column.

xlYourRange = xlWorksheet.get_Range("A1").EntireColumn;

EDIT:

Dates are a bit more complicated and will also depend on your regional settings:

// Results in a Date field of "23/5/2011"

xlRange.NumberFormat = "DD/MM/YYYY";
xlRange.Value = "23/5/2011";

// Results in a Custom field of "23/5/2011"

xlRange.NumberFormat = "DD-MM-YYYY";
xlRange.Value = "23/5/2011";

// Results in a Custom field of "05/23/2011"

xlRange.NumberFormat = "MM/DD/YYYY";
xlRange.Value = "5/23/2011";

// Results in a Custom field of "05-23-2011"

xlRange.NumberFormat = "MM-DD-YYYY";
xlRange.Value = "5/23/2011";

// Results in a Date field of "23/05/2011"

xlRange.NumberFormat = "DD/MM/YYYY";
xlRange.Value = "5/23/2011";

// Results in a Custom field of "23-05-2011"

xlRange.NumberFormat = "DD-MM-YYYY";
xlRange.Value = "5/23/2011";

// Results in a Custom field of "23/5/2011"

xlRange.NumberFormat = "MM/DD/YYYY";
xlRange.Value = "23/5/2011";

// Results in a Custom field of "23/5/2011"

xlRange.NumberFormat = "MM-DD-YYYY";
xlRange.Value = "23/5/2011";
like image 156
Sid Holland Avatar answered Oct 06 '22 01:10

Sid Holland