My problem is that I am trying to set data type to an excel column in C#, in this case the data types number, text and date. I am using the DLL Microsoft.Office.Interop.Excel. I don´t know how to set those formats to the cells of an entire excel column using C# has programming language.
问题:
回答1:
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";
回答2:
There is an answer to a question I asked on this some time back.
Most notably, the data types this guy uses in his answer are:
private struct ExcelDataTypes
{
public const string NUMBER = "NUMBER";
public const string DATETIME = "DATETIME";
public const string TEXT = "TEXT"; // also works with "STRING".
}
Look familiar?
If you are interested, here is the link:
Insert DataTable into Excel Using Microsoft Access Database Engine via OleDb
回答3:
Yes, with the date format everything is more complicated - even more complicated than Sid Holland has mentioned. The reason is in some localization problems. For example, if your Windows system has Russian localization, you should use Russian letters in the date formats, like "ДД.MM.ГГГГ" or "ГГГГ-MM-ДД", and, therefore, you should be able to extract and apply these letters. See more or less complete description and solution here: https://stackoverflow.com/a/35418176/2199512