简体   繁体   中英

Opening Excel ODBC connection from C#

I'm looking to create a process that opens several excel files and just refreshes them. I have code:

   excel.Visible = true;
    Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open("Testfile.xlsx");

    workbook.RefreshAll();
    workbook.Save();

The issue is that because on these worksheets the connections are set to refresh in the background it is trying to save before it has finished refreshing. I know i need to set BackgroundQuery = false, but I don't know how to access the already existing connections. Any help is appreciated.

So I didn't manage to get this specific code to work, but by trial and error I figured out that:

foreach (Microsoft.Office.Interop.Excel.WorkbookConnection i in workbook.Connections)
        { System.Console.WriteLine(i.Name);
        i.OLEDBConnection.BackgroundQuery = false;
        }

works.

I don't know much C, so the syntax may be wrong, but it's the worksheet.querytable object that you want:

Microsoft.Office.Interop.Excel.Worksheet ws = workbook.worksheets(1)
Microsoft.Office.Interop.Excel.Worksheet qt = ws.querytables(1)

ws.QueryTables(1).RefreshOnFileOpen = False
ws.QueryTables(1).BackgroundQuery = False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM