【发布时间】:2017-05-18 05:20:09
【问题描述】:
我正在尝试读取 Excel 文档以获取选中复选框的列表。
- 我找到了一个解决方案here 用于在 Word 中定位复选框 使用 OpenXML 的文档,但不能将其用于复选框 Excel。看来CheckBox Class 是为 文字处理文档,而不是 Excel。
下面的代码显示了所有复选框的列表,但无论我做什么,我都无法访问它们的值。 有什么想法吗?
C#代码:
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;
还有什么建议吗?
【问题讨论】:
标签: c# excel openxml openxml-sdk