Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 275
Stefan Olsson Avatar asked Oct 15 '25 14:10

Stefan Olsson


2 Answers

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.

like image 75
Snake Avatar answered Oct 18 '25 04:10

Snake


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
like image 33
Jordan Avatar answered Oct 18 '25 04:10

Jordan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!