【问题标题】:Listing and refreshing all Pivot tables列出并刷新所有数据透视表
【发布时间】:2014-09-15 08:04:56
【问题描述】:

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

为此,我使用此脚本(因为我每天 9 点自动启动此脚本)。

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#,所以我有点迷路了。这个问题可能有一个更简单的解决方案,任何提示都表示赞赏。

【问题讨论】:

标签: c# excel pivot-table


【解决方案1】:

一年过去了,我猜你已经找到了解决问题的方法……也就是说,为了后代的利益,我也在寻找类似问题的解决方案。

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

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

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

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

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

但是,让我对您的问题感到困惑的一件事是,我的印象是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++)
}

【讨论】:

    【解决方案2】:

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

    pt.Refresh();
    

    【讨论】:

      猜你喜欢
      • 2017-04-08
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 2016-01-11
      • 1970-01-01
      相关资源
      最近更新 更多