列出并刷新所有数据透视表

我试图创build一个脚本,刷新工作表中的所有数据,然后刷新数据透视表之后(因为数据透视表中的数据通常刷新数据库中的数据结果是默认情况下不正确)。

要做到这一点,我使用这个脚本(因为我每天在9.00自动启动此脚本)。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // Get fully qualified path for xlsx file var spreadsheetLocation = "C:\\update_rapport\\Salgsrapport.xlsx"; var exApp = new Microsoft.Office.Interop.Excel.Application(); var exWbk = exApp.Workbooks.Open(spreadsheetLocation); //var exWks = (Microsoft.Office.Interop.Excel.Worksheet)exWbk.Sheets["responses(7)"]; exWbk.RefreshAll(); exApp.DisplayAlerts = false; // This part is not correct. Need to find all pivot tables and update them Object PivotTables( Object Index ); string save_file_name = "C:\\temp\\updated\\Salgsrapport.xlsx"; exWbk.SaveAs(save_file_name); exWbk.Close(true); exApp.Quit(); } } } 

我发现循环所有数据透视表最接近的是: http : //msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.pivottables.aspx

然而,这不是一个完整的例子,我从来没有真正的C#编程,所以我有点迷失在这里。 这个问题可能有一个更简单的解决scheme,任何提示是赞赏。

自从一年后,我猜你已经find了解决问题的办法……为了子孙后代的利益,我也在寻求解决类似问题的办法。

据我所知,在工作簿级别的PivotCaches方法似乎公开所有数据透视表对象。 我仍然在解决我的问题,但如果你的目标是刷新所有数据透视表,那么这样的事情应该工作:

 foreach (Microsoft.Office.Interop.Excel.PivotCache pt in exWbk.PivotCaches()) pt.Refresh(); 

我确实知道,如果你知道数据透视表的名字,你可以这样做:

 exWbk.Sheets["Sheet1"].PivotTables["PivotTable1"].PivotCache.Refresh(); 

我已经使用了一段时间了。

但是,有一件事让我对你的问题感到困惑,那就是我感到exWbk.RefreshAll(); 刷新工作簿中的每个对象并考虑相关性。 我惊讶地发现,调用它并没有更新数据透视表。

更新:

我在这find了更好的解决scheme。 这就是我一直在寻找的开始。

http://www.pcreview.co.uk/threads/vsto-how-to-find-all-pivot-tables-in-the-workbook.3476010/

 Excel.PivotTables pivotTables1 = (Excel.PivotTables)ws.PivotTables(Type.Missing); if (pivotTables1.Count > 0) { for (int j = 1; j <= pivotTables1.Count; j++) } 

foreach(Microsoft.Office.Interop.Excel.PivotCache pt在exWbk.PivotCaches())

 pt.Refresh();