2013-05-09 96 views
2

我試圖通過C#獲取XLS文檔中存在的複選框的狀態。讓我回到這裏。這是我有:C#:MS Excel中複選框的狀態

  • MS Office 2007的+開發工具和VC#2010速成
  • 引用的MS Excel的12.0對象庫
  • 的XLS文件

我成功地檢索Excel中。形狀對象。然而,當我試圖確定它是否被選中時,我被卡住了。到目前爲止,我已經獲得了它的AutoShapeType,它說msoShapeMixed。

有人能指引我走向正確的方向嗎?謝謝!

class Program { 
    static void Main(string[] args) { 
     Application excel = new Application(); 
     Workbook wb = excel.Workbooks.Open(
     "document.xls", 
     Missing.Value, Missing.Value, Missing.Value, Missing.Value, 
     Missing.Value, Missing.Value, Missing.Value, Missing.Value, 
     Missing.Value, Missing.Value, Missing.Value, Missing.Value, 
     Missing.Value, Missing.Value 
    ); 
     Worksheet ws = wb.Worksheets[3]; 
     Microsoft.Office.Interop.Excel.Shape sh = ws.Shapes.Item("checkbox1"); 
     Console.WriteLine("[" + (sh.AutoShapeType.ToString()) + "]"); // msoShapeMixed 
     Console.ReadLine(); 
    } 
    } 
+0

那麼,由於該項目可以作爲圖片獲得,使用Copy()或CopyPicture(),可以分析圖片本身並以此方式找出狀態。然而,這種做法聽起來相當絕望。 – 2013-05-10 06:00:50

回答

2

我已經解決了這個問題與VB的幫助和建立類lib。這個庫在C#中使用。

VB:

Option Strict Off 
Imports Excel = Microsoft.Office.Interop.Excel 

Public Class CheckboxReader 
    Dim xlApp As Excel.Application = Nothing 
    Dim xlWorkBooks As Excel.Workbooks = Nothing 
    Dim xlWorkBook As Excel.Workbook = Nothing 
    Dim xlWorkSheet As Excel.Worksheet = Nothing 

    Public Sub New(ByVal excelFilename As String, ByVal worksheetName As String) 
     xlApp = New Excel.Application 
     xlApp.DisplayAlerts = False 
     xlWorkBooks = xlApp.Workbooks 
     xlWorkBook = xlWorkBooks.Open(excelFilename) 
     For Each worksheet As Excel.Worksheet In xlWorkBook.Worksheets 
      If worksheet.Name = worksheetName Then 
       xlWorkSheet = worksheet 
       Exit For 
      End If 
     Next 
    End Sub 

    Public Function GetCheckBoxValue(ByVal Name As String) As Boolean 
     Dim found As Boolean = False 
     Dim result As Boolean = False 
     If Not found Then 
      result = xlWorkSheet.OLEObjects(Name).Object.Value() 
      found = True 
     End If 
     Return result 
    End Function 
End Class 

C#:

CheckboxReader chr = new CheckboxReader(excelFilename, worksheetName); 
bool typeFabInstall = chr.GetCheckBoxValue("checkboxName"); 

的偉大工程。祝你好運!

+2

是的,不得不去VB去完成這些工作。謝謝! – 2013-05-14 20:59:16

+0

我試着實現你的解決方案,互操作在VB中的行爲與C#中的行爲一樣。 xlWorkSheet.OLEObjects不返回對象 – Marek 2016-07-07 10:49:58

+0

如果你願意,我可以與你分享編譯的dll文件嗎?如果是的話,給我發電子郵件。 – Kaster 2016-07-07 13:59:38