Friday 18 November 2011

Excel (2010) Automation with C# (Continued)

In my last post I left it with the problem with how do you know that a cell value received as a double needs to be treated as a date. At this point in time I haven't found a complete solution but have found a sufficient solution for my problem.

Parameters in my command are identified as being curly braces surrounding a type and a column reference

e.g. {S2} refers to a string in column 2, while {N4} refers to a number in column 4 (The row is the same as command)

As I know what I'd like to be formatted as a date it was just a case of adding a new type identifier D for date so that I now have {D3} to refer to a date in column 3. I can then use DateTime.FromOADate() to parse the double and return a date time. This can then be output as a yyyy/mm/dd string in the parameter substitution

DateTime dt = DateTime.FromOADate(r.Value2);

Future Changes
Currently the command is processed as soon as you leave the cell, what I'd like to do is to be able to write the commands and then  select a range of cells and choose to convert them at that point. This way I could make sure I was happy with the entire thing before I lost all my parameter markers.

The other sensible change may be to  leave the initial string along and have the actual fully substituted string returned in the next column across, This way you don't lose your original command.