Search code examples
c#excelformattingcell

C# Accessing EXCEL, formatting cell as General


When manipulating excel cells in C# (via an COM object), should I use the .Value or .Value2 ? that is

 sheet.Cells[row + n, col].Value = "Hello world"

or

 sheet.Cells[row + n, col].Value2 = "Hello world"

What is the difference between them to ?

Also, how do I set a cell format to "General" ?

sheet.Cells[row + n, col].NumberFormat = "XYZ";  // Not sure what should be here

Right now when I assign a cell with the number "0,34" and even if I do

sheet.Cells[row + n, col].NumberFormat = "@"; 

I get this "little error" sign up in the left corner in each cell


Solution

  • To answer the first question you should read this article: http://blogs.msdn.com/b/eric_carter/archive/2004/09/06/225989.aspx

    The optional parameters part doesn't apply anymore since C# 4.0 has optional parameters.

    But there IS a difference (stated in the article)

    The only difference between this property [Value2] and the Value property is that the Value2 property doesn’t use the Currency and Date data types. You can return values formatted with these data types as floating-point numbers by using the Double data type.

    For the second question, have you tried setting a cell to 'General' and reading it out in code?

    I think it's sheet.Cells[row + n, col].NumberFormat = "General", where "@" is pure text.