我正在尝试阅读Excel文档以获取已选中复选框的列表。
下面的代码显示了所有复选框的列表,但无论我做什么,我都无法访问它们的值。 任何想法?
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(@"C:\test.xlsx", false))
{
WorkbookPart workBookPart = spreadsheetDocument.WorkbookPart;
foreach (Sheet s in workBookPart.Workbook.Descendants<Sheet>())
{
if (s.Name.ToString().Equals("Sheet1"))
{
WorksheetPart wsPart = workBookPart.GetPartById(s.Id) as WorksheetPart;
foreach (DocumentFormat.OpenXml.Spreadsheet.Control cb in wsPart.Worksheet.Descendants<DocumentFormat.OpenXml.Spreadsheet.Control>())
{
if (cb.Name.ToString().IndexOf("CheckBox") > -1)
{
textBox1.AppendText(cb.Name + "\n");
}
}
}
}
}
事实证明,我们正在使用Active X控件。以下代码能够正确定位复选框,这是一个非常低性能的解决方案,但不使用OpenXML:
var xlApp = new Excel.Application();
var xlWorkbook = xlApp.Workbooks.Open(xlFileName);
var xlSheet = xlWorkbook.Worksheets["Sheet1"] as Excel.Worksheet;
StringBuilder x = new StringBuilder();
try
{
Excel.OLEObjects oleObjects = xlSheet.OLEObjects() as Excel.OLEObjects;
foreach (Excel.OLEObject item in oleObjects)
{
if (item.progID == "Forms.CheckBox.1")
{
VBE.CheckBox xlCB = item.Object as VBE.CheckBox;
if (xlCB.get_Value())
x.Append(item.Name + ": checked");
else
x.Append(item.Name + ": not checked");
Marshal.ReleaseComObject(xlCB); xlCB = null;
}
}
Marshal.ReleaseComObject(oleObjects); oleObjects = null;
}
catch (Exception ex){ }
Marshal.ReleaseComObject(xlSheet); xlSheet = null;
xlWorkbook.Close(false, Missing.Value, Missing.Value);
Marshal.ReleaseComObject(xlWorkbook); xlWorkbook = null;
if (xlApp != null)
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
xlApp = null;
还有其他建议吗?
答案 0 :(得分:1)
假设您正在使用表单控件CheckBox ,这些行中的某些内容应该会有所帮助:
score = dictionary["r"] as? Double ?? 0
与MS Word不同,Excel具有表单控件和 Active X控件。您可以阅读差异here