2010-05-06 42 views
3

是否有可能找出格式的Excel單元格我知道有.NumberFormat但它返回格式但不是類型...基本上我需要知道它是否是自定義的然後它應該返回自定義,如果它是貨幣它應該返回貨幣或任何其他數據類型 請幫我如何知道Excel單元格的格式

回答

3

在這種情況下,Excel以特殊方式存儲值(大多數數據類型實際上是雙精度值),這使得在沒有Excel幫助的情況下檢測單元格格式變得非常棘手。

因此,我建議您可以利用內置的Excel的CELL功能,而在於自己詢問的數據類型:

enter image description here

private void button1_Click(object sender, EventArgs e) 
{ 
    //C1 is a cell I use to evaluate the Format of Cells A1 thru to A7 
    using (var rnEvaluate = xlApp.Range["C1:C1"].WithComCleanup()) 
    { 
     for (int i = 1; i < 8; i++) 
     { 
      rnEvaluate.Resource.Value2 = "=CELL(\"format\",A" + i.ToString() + ")"; 
      string cellFormat = GetExcelCellFormat(rnEvaluate.Resource.Value2); 
      System.Diagnostics.Debug.Write(cellFormat); 
     } 
    } 
} 

private string GetExcelCellFormat(string cellFormat = "G") 
{ 
    switch (cellFormat.Substring(0, 1)) 
    { 
     case "F" : 
      return "Number"; 
      break; 
     case "C": 
      return "Currency"; 
      break; 
     case "D": 
      return "Date"; 
      break; 
     default : 
      return "General"; 
      break; 
    } 
} 

PS的.WithComCleanup()是因爲我使用VSTO Contrib

0

這取決於,如果它是一個xslx文件(Open XML Excel),那麼你可以解壓縮xlslx文件(xlsx是一個zip文件),然後檢查該特定單元格的xl \ worksheets \ sheet {?}。xml文件。

雖然這可能是一個過於複雜的方式。

+0

它如果不是過於複雜這些任務需要在服務器KB257757上完成。問題是像這樣的方法,我的單元格數據類型描述不完整,例如在XML中,數字單元格不指定小數位:'':( – 2012-12-21 03:18:02

0

從Excel範圍中獲取NumberFormat後,可以使用this table of formatting codesthis reference from Microsoft進行轉換。請記住,如果自定義,混合格式是可能的。

如果你只是想的基本值(默認我從2010下降下來在Excel中):

  • 「0.00」 - 數
  • 「$#,## 0.00」 - 外幣
  • 「 _($ *#,## 0.00 _); _($ *(#,## 0.00); _($ *「」 - 「」?? );(@_)「 - Accounting
  • 」 m/d/yyyy「 - 短日期
  • 」[$ -F800] dddd,mmmm dd,yyyy「 - 長日期
  • 「[$ -F400] H:MM:SS AM/PM」 - 時間
  • 「0.00%」 - 百分比
  • 「?#/」 - 分數
  • 「0.00E + 00」 - 科學
  • 「@」 - 文本
  • 「大將軍」 - 通用

我通過錄制宏和修改所選單元格的數字格式得到這些值。


編輯:
多一點幫助,以得到你想要去的 - 假設你正在使用Excel互操作庫(我知道如何訪問NumberFormat功能的唯一途徑):

string fileName = @"c:\Book1.xlsx"; 
Application app = new Application(); 
Workbook wb = app.Workbooks.Open(fileName, 
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
    Type.Missing, Type.Missing); 
Worksheet sheet = wb.Sheets[1]; //Change to the sheet you care about (1 based index) 
var cell = sheet.Cells[1, 1]; //Change to the cell you care about (1 based index) 
string cellNumberFormat = cell.NumberFormat; //Number format of cell to compare against known values 

使用interop庫的設置發現here

+1

也可以隨時更改如果你覺得你所標記的那個不足以滿足你的需求,那麼接受的答案就是 – 2012-12-20 16:28:25

+1

這不會回答Jon,嘗試'NumberFormat' - 儘管單元格是Currency,Date或者 – 2012-12-21 02:13:21

+0

@Jeremy - 當我設置了單元格號碼格式時,看到我上面的編輯'NumberFormat'返回前面提到的值,並在提供的鏈接中找到。 – 2012-12-21 17:03:46