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

Ole*_*røm 5 c# excel pivot-table

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

为此,我使用此脚本(因为我每天在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();

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Ham*_*one 6

自从一年后,我猜你已经找到了解决问题的方法......为了后代的利益,我也在寻找类似问题的解决方案.

据我所知,工作簿级别的PivotCaches方法似乎暴露所有数据透视表对象.我仍在处理我的问题,但如果您的目标是刷新所有数据透视表,那么这样的事情应该有效:

foreach (Microsoft.Office.Interop.Excel.PivotCache pt in exWbk.PivotCaches())
    pt.Refresh();
Run Code Online (Sandbox Code Playgroud)

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

exWbk.Sheets["Sheet1"].PivotTables["PivotTable1"].PivotCache.Refresh();
Run Code Online (Sandbox Code Playgroud)

我已经成功使用了一段时间.

然而,让我对你的问题感到困惑的一件事是,我的印象是exWbk.RefreshAll();刷新工作簿中的每个对象并考虑依赖关系.我很惊讶地听到调用它也没有更新数据透视表.

更新:

我在这里找到了更好的解决方案 这就是我一直在寻找的东西.

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++)
}
Run Code Online (Sandbox Code Playgroud)