问题
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