2011-10-11 50 views
2

C#,Visual Studio 2010中C#訪問EXCEL,格式化單元作爲通用

當Excel細胞在C#(經由COM對象)操縱,我應該使用。價值或.Value2? 是

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

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

是什麼它們之間的區別?

另外,如何設置單元格格式爲「常規」?

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

現在,當我分配一個小區甚至如果我做

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

我得到這個「小錯誤」,數字「0.34」,並在每個單元中的左上角註冊

回答

4

要回答第一個問題,你應該看看這篇文章:http://blogs.msdn.com/b/eric_carter/archive/2004/09/06/225989.aspx

的可選參數的部分不適用了,因爲C#4.0具有可選參數。

但有區別(在文章中說明)

這個屬性[值]與值 屬性之間的唯一區別是,Value 2屬性不使用貨幣和日期 數據類型。您可以使用Double數據類型將使用這些數據類型格式化的值返回爲浮點數 。

對於第二個問題,你有沒有嘗試過設置一個單元格爲「常規」並在代碼中讀出它?

我認爲這是sheet.Cells[row + n, col].NumberFormat = "General",其中"@"是純文本。

+0

感謝您的文章,我現在看到的差異,如果我使用「一般」,我得到的錯誤「屬性NumberFormat不能用於類的範圍」 –

0

爲了獲得常規類型,作爲應該分配給NumberFormat屬性的「魔術字符串」,嘗試使用空字符串,例如

sheet.Cells[5, 7].NumberFormat = ""; // sets the cell type to the General type