1

I have a problem with automating Excel that I cannot solve. I want to mimic the "Import External Data" feature. It works already perfectly for flat tables, but not for PivotTables, when I select multiple database tables for the import.

The manual way

I have an Access database with 2 tables (accounts and transactions), linked by a foreign key ("account" in transactions table). I want to import both immediately to a PivotTable. The usual way would be to click on "Data" -> "External Data", then select both tables in the dialog, then choose "PivotTable report" and click "OK". Now the PivotTable is in the active sheet and on the right side there is the Field List which offers all fields in the hierarchy of the imported tables.

This is what I want to mimic for the mentioned database file. Does anyone have an idea how this works?

What I tried

I have already tried to record and adapt a macro, to no avail, as it records incomplete and flawed code. Incomplete because the recorded code does not feature the creation of a data model, but that is obviously necessary (?). Flawed because the code does not run, its syntax is incorrect.

I can successfully create a PivotTable from one database table like this:

Excel.PivotCaches pivotCaches = workbook.PivotCaches();
Excel.PivotCache pivotCache = pivotCaches.Create(Excel.XlPivotTableSourceType.xlExternal,
    Type.Missing, Type.Missing);
pivotCache.Connection = conStr;
pivotCache.MaintainConnection = true;
pivotCache.CommandText = "Accounts";
pivotCache.CommandType = Excel.XlCmdType.xlCmdTable;

Excel.PivotTables pivotTables = sheet.PivotTables();
Excel.PivotTable pivotTable = pivotTables.Add(pivotCache, sheet.get_Range("A3", "C20"), "Pivot", Type.Missing, Type.Missing);

But it fails in each of the many attempts I tried to get more than one database table.

What is the way to go for multiple tables?

Bear in mind that I do not necessarily know the table names and the join fields, plus I do not want to lose the distinction between the tables, it should be preserved in the PivotTable field list for hierarchical choice of the fields. Furthermore, a catch-all SQL query would be a serious impairment to performance.

Please help me!

PS: I am on Office 2013 with C# as my language of choice.

/edit1: Later I would also want the PivotTable to refresh if the database tables change (manually invoking that refresh).

/edit2: I would also be entirely satisfied with a way to use multiple worksheets as sources for a PivotTable, as long as they appear separately in the Field List.

4

0 回答 0