本文介绍了C#:MS Excel中复选框的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过C#获取XLS文档中存在的复选框的状态.让我备份到这里.这就是我所拥有的:

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 +开发工具和VC#2010 Express
  • 参考的MS Excel 12.0对象库
  • XLS文档

我成功检索了Excel.Shape对象.但是,在尝试确定是否选中它时,我陷入了困境.到目前为止,我已经获得了它的AutoShapeType,它表示为msoShapeMixed.

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

推荐答案

我已经在VB的帮助下解决了这个问题,并建立了类库.此lib在C#中使用.

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");

效果很好.祝你好运!

这篇关于C#:MS Excel中复选框的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:46