C# Accessing EXCEL, formatting cell as General

你说的曾经没有我的故事 提交于 2019-12-06 11:51:22

问题


C#, Visual studio 2010

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


回答1:


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.




回答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


来源:https://stackoverflow.com/questions/7724403/c-sharp-accessing-excel-formatting-cell-as-general

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!