3

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

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Stefan Olsson
  • 617
  • 3
  • 16
  • 32

2 Answers2

5

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.

Anemoia
  • 7,928
  • 7
  • 46
  • 71
  • Thanks for the article, I see now the difference, If I use "General" I get the error "The property NumberFormat can not be used on the class Range" – Stefan Olsson Oct 11 '11 at 12:49
2

In order to get the General type, as "magic string" that should to be assigned to the NumberFormat property try to use the empty string, e.g.

sheet.Cells[5, 7].NumberFormat = "";  // sets the cell type to the General type
Jordan
  • 585
  • 1
  • 7
  • 18