简体   繁体   English

C#:MS Excel中复选框的状态

[英]C#: State of a Checkbox in MS Excel

I am trying to acquire state of a checkbox existing in an XLS document via C#. 我正在尝试通过C#获取XLS文档中存在的复选框的状态。 Let me back up here. 让我备份到这里。 This is what I have: 这就是我所拥有的:

  • MS Office 2007 + Dev Tools and VC# 2010 Express MS Office 2007 +开发工具和VC#2010 Express
  • Referenced MS Excel 12.0 Object Library 引用的MS Excel 12.0对象库
  • An XLS document XLS文件

I successfully retrieve the Excel.Shape object. 我成功检索了Excel.Shape对象。 However, I am stuck when trying to determine whether it is checked or not. 但是,在尝试确定是否已检查时,我陷入了困境。 So far I have acquired its AutoShapeType, which says msoShapeMixed. 到目前为止,我已经获得了它的AutoShapeType,即msoShapeMixed。

Can someone point me to the right direction? 有人可以指出我正确的方向吗? Thanks! 谢谢!

  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();
    }
  }

I have resolved this problem with help of VB and build class lib. 我已经在VB的帮助下解决了这个问题,并建立了类库。 This lib used in C#. 此lib在C#中使用。

VB: 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#: C#:

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

Works great. 效果很好。 Good Luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM