Format Entire Excel Column Using C# - c#

I have column F that I want to format as money so add $ sign and commas. It's to late for me to attempt to format it in the Source so I was going to format it via C# after all data has been written to Excel. I know you can use this syntax to change a column to a date - what would be the appropriate syntax for money?
range.EntireColumn.NumberFormat = "MM/DD/YYYY";

Sorry for my stupidity on this one...it's actually quiet simple
range3.EntireColumn.NumberFormat = "$#,##0.00";

Related

C# convert Date to text in cell in Excel (interop)

I have a pretty specific problem with the "Automatic data conversions" that Excel is doing. First I'll try to explain what exactly I'm doing and how Excel is making fun of me ;)
My program is creating a Charts for reports from temperature sensors. In the reports the first Column is the date of the reading and the second column is the reading of the sensors for that date. The problem is the automatic selection of the "XAxis series" that Excel is doing, if the first column is in DateTime format:
Here is the example for what Excel is doing with the Charts if it "smells" Date format...
And Here is how the chart looks if the first column is in Text format.
I tried some variants to convert the values in the first column but everything is too slow or messes up the values.
So far the "fastest" way that I found is:
foreach(Range cell in firstCol.Cells)
{
if (cell.Value is DateTime && !(cell.Value).ToString().Contains("\'"))
{
cell.Value = "\'" + cell.Value;
}
}
But that's not fast enough. Imagine a 100 sheets (1 sheet for each sensor) and each sheet with between 2500 and 4000 rows.
I tried things like:
usedRange.NumberFormat = "#";
as it was suggested in a couple of places on internet but that doesn't work for Date formats. It converts this:
01/12/2016 00:30 like this: 42705.02083.
So my question is if someone can suggest a better or faster way to convert the dates or to make Excel read the DateTime as text without messing up anything.
I'm sure there's a better way by fixing the X axis itself, but if all your looking for is to get the date in text format, the quick fix would be something like:
=TEXT(DATE(2016,1,12)+TIME(0,30,0),"MM/dd/yyyy hh:mm")

Excel format function equivalent in c#

I have an application that uses excel. The user needs to write an excel format in my application and I need to place it excel to some cells. However I need to provide an example to the user to know if the format will be correct or not.
I know in VBA there is the function FORMAT. Is there an equivalent in C# for this function?
It needs to work for example with the format "[$-409]d.m.yy h:mm AM/PM;#" but it has to support anything that the Excel supports.
This was bothering me too. I didn't want to have to apply NumberFormat to the cells, paste the values and then retrieve the text.
After some investigation, I found the function that does this.
WorksheetFunction.Text: https://msdn.microsoft.com/en-us/library/office/ff841121.aspx
The first argument is the value that you want to format, this could be a String, DateTime, Double, Integer etc, the second argument is the Excel NumberFormat string.
MessageBox.Show(ExcelApp.WorksheetFunction.Text(DateTime.Now, "[$-409]d.m.yy h:mm AM/PM;#"));

Excel Shows "#########" when i try to write DateTime.Now.tostring() to one of the cell in Excel File

I have created a application in c# , it reads excel file and after checking some conditions, it select a row to be written in another Excel File.
Everything is working fine, but i need to end the file with the DateTime.Now.ToString().
string date = DateTime.Now.ToString();
ExcelWorkSheet2.Cells[newFileRow, 1] = date;
When I see the file created, it shows "########" symbol instead of actual date. When I select that cell , it changes to correct date format.
What may be going wrong?
##### is typically shown by Excel when the value in the cell is too wide. What happens if you try to expand the column width a little bit?
You need to expand the size of the cell to make it display properly. This is most easily done by double clicking on the column header to make it expand to fit all data.
Just try widening the column display a little.
As the others have said, the column isn't wide enough for your datetime value.
Without putting anything in the brackets, DateTime.Now.ToString() will return every detail of the current date.
You can cut this down by putting some speech marks in between the brackets, followed by some formatting information.
dd for current date
MM for current month
yyyy for current year
hh for current hour
mm for current minute (notice the lowercase)
ss for current second
So for example, if you just wanted the date without any time information, you would put the following which would return 2012-03-25:
var thisString = DateTime.Now.ToString("yyyy-MM-dd");
Thanks
I think you might want to shorten DateTime format and/or widen your cell a bit.
Please refer to this information on DateTime formatting.
More:
DateTime.Now.ToString() usually produces long string, something like "3/25/2012 7:26:26 PM". If this is something you would like to display, then the only option for you is to make your cell/column wider.
Otherwise consider one of many formats that suit you well.
Example: DateTime.Now.ToString("MM-dd-yy")

DateTime problem when day <= 12

I've looked around a lot and short of writing a horrible chunk of code to manipulate the string, I'd like to ask if anyone knows a nice way of sorting it:
I have a bunch of date strings in cells that I'm pulling out such as:
03/05/2011
27/05/2011
31/05/2011
03/05/2011
09/05/2011
31/05/2011
etc.
While I'm reading any entires where the day can be construed as a month - i.e. entries 1, 4 and 5 above - it gets put in as a DateTime with the day and month swapped.
For example, 03/05/2011 gets read in as a DateTime "05/03/2011 00:00:00"
The others are all read and nicely provide me with a simple string of "27/05/2011".
I'm getting this info from Excel, using
((Excel.Range)worksheet.Cells[rowCount, 3]).Value.ToString()
If I try Value2 as with my other lines, it reads those odd dates as things like "40607" but again, will read the other dates normally.
If you use the DateTime.ParseExact function to convert a string to a DateTime object, you can specify the specific format used by your dates (which looks like "day/month/year") without having to do any string manipulation whatsoever.
Example:
var dateString = "03/05/2011";
var format = "dd/MM/yyyy";
var date = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
More information on custom Date and Time format strings can be found here.
EDIT: Try using the DateTime.FromOADate method to convert the value returned by the Range.Value2 property to a DateTime object, e.g. something like this:
var dateTime = DateTime.FromOADate(((Excel.Range)worksheet.Cells[rowCount, 3]).Value2);
DateTime.ParseExact Method converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information.
The format of the string representation must match the specified format exactly.
String dateString = "15/06/2008";
String format = "dd/MM/yyyy";
DateTime result =
DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
That sounds like a localization problem. Try setting your locale implicititly. For example in WPF application it's something like:
System.Threading.Thread.CurrentThread.CurrentCulture =
new System.Globalization.CultureInfo("en-US");
I have a bunch of date strings in cells that I'm pulling out such as:
No, you don't. You have a mix of strings that look like dates and dates that look like strings. This is an Excel issue, not a C# issue.
Not sure if you are creating the spreadsheet, or if you are getting it from somewhere else. But it the problem is that Excel attempt to parse text as it is entered in the cell. In this case, it is making some wrong decisions about the dates it finds.
If you enter a date like "03/05/2011", Excel will (incorrectly) parse it as March 5th, 2011, and store that as a numeric date code (40607). It then applies a date formatting to the cell (it uses m/d/yyyy on my machine).
If you enter a date like "31/05/2011", Excel can't parse it as a date, and it stores it as text.
To prove this, select the cells and go to Edit > Clear > Formats. All the "bad dates" will just show as numbers, all the rest will stay looking like dates.
You have a few choices:
Fix the data before its entered into Excel (prepend everything with a ' so its all entered as text, or make sure to create the spreadsheet on a machine that has the right date settings.)
Don't use the .Value.ToString() from Excel, just use .Text. This will ignore the bad parsing that Excel did, and should give you a consistent text value (from both types) that you can ParseExact with C#, per the other answers.
(2) is a lot easier, and if the spreadsheets already exist, may be your only choice.
The problem is because your Dates are being read as american culture or similar.
If you use the following you can specify the format you expect your dates to be in:use
DateTime result;
if(DateTime.TryParseExact("dd/MM/yyyy", out result))
{
// Got an English date
}

Prevent TestContext data from being automagically converted

I am parameterising my test cases by using data read from .csv files. One of the columns in the csv file has simple date values (as regular strings) in US format, eg mm/dd/yyyy. When the data is actually read and populated into a TestContext however, TestContext.DataRow["MyDateColumn"] actually returns a converted System.DateTime object, complete with a timestamp of 12:00:00 AM. I absolutely do not require or want this automatic conversion. How do I stop this from happening?
If the type of the MyDateColumn is set to datetime, then it would/should return a datetime object.
Try changing the type of MyDateColumn to be string and see if that does the trick.
UPDATE
Change dates in the CSV so that they are "mm/dd/yyyy" instead of mm/dd/yyyy.
DateTime.Parse(TestContext.DataRow["MyDateColumn"], CultureInfo.InvariantCulture).ToShortDateString()
I got solution for this :)
I just put ' before actual data. When I retrieve data, data comes as is. Before using it, I remove ' from data with substring method.
I remember using this technique on excel to make numbers appear as text. It worked for me.
I put double qoutes around the data. That gives back strings, without removing the quotes.
columnInt, columnString
1, "11.12.89"
2, "12.12.89"

Categories

Resources