C#: State of a Checkbox in MS Excel

与世无争的帅哥 提交于 2021-02-08 05:16:30

问题


I am trying to acquire state of a checkbox existing in an XLS document via C#. Let me back up here. This is what I have:

  • MS Office 2007 + Dev Tools and VC# 2010 Express
  • Referenced MS Excel 12.0 Object Library
  • An XLS document

I successfully retrieve the Excel.Shape object. However, I am stuck when trying to determine whether it is checked or not. So far I have acquired its AutoShapeType, which says 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();
    }
  }

回答1:


I have resolved this problem with help of VB and build class lib. This lib used in 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");

Works great. Good Luck!



来源:https://stackoverflow.com/questions/16459450/c-state-of-a-checkbox-in-ms-excel

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