问题
Using Excel Interop, I'm attempting to loop through all QueryTables in all Worksheets and delete them. I've got this code, which works:
> // loop through each Worksheet
> for (int i = 1; i <= workbook.Sheets.Count; i++)
> {
> sheet = (Worksheet)workbook.Sheets.get_Item(i);
>
> // loop through each queryTable on each Worksheet
> int queryTableCount = sheet.QueryTables.Count;
> for (int j = 1; j <= queryTableCount; j++) {
> sheet.QueryTables.Item(1).Delete();
> }
> }
This works just fine for some data connections/files, but for others the "QueryTables.Count" returns zero - even though I know that there are connections. The connections were created in Excel 2007 via the Data tab-->From Other Sources-->From Microsoft Query. Has anyone run into this problem?
回答1:
I figured out the issue, thanks to this post. It turns out that Excel Interop handles query tables differently in the 2003 vs. 2007 versions of Excel. 2007 uses ListObjects, so use the same code to loop through each Worksheet like above, but then use:
// loop through each list object on each Worksheet
if (sheet.ListObjects.Count > 0)
{
foreach (ListObject obj in sheet.ListObjects)
{
obj.QueryTable.Delete();
}
}
来源:https://stackoverflow.com/questions/5425962/deleting-all-querytables-in-excel-2007-workbook