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

时间:2014-09-15 08:04:56

标签: 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();

        }

    }
}

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

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

2 个答案:

答案 0 :(得分:5)

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

据我所知,工作簿级别的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++)
}

答案 1 :(得分:0)

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

pt.Refresh();
相关问题