简体   繁体   English

如何使用 C# 更新 Excel PIvot 表数据

[英]How to update Excel PIvot Table data using C#

let me outline my requirement.让我概述一下我的要求。 I have an excel spreadsheet with multiple pivot tables ( linked to charts / slicers etc ) and 2 worksheets with the data that those pivot tables refer to.我有一个 excel 电子表格,其中包含多个 pivot 表(链接到图表/切片器等)和 2 个工作表,其中包含 pivot 表所指的数据。 Currently I have to manually execute a SQL query, copy the data, paste it over the current data in the spreadsheet and then refresh the pivot tables every day.目前我必须手动执行 SQL 查询,复制数据,将其粘贴到电子表格中的当前数据上,然后每天刷新 pivot 表。

This is sub-optimal at best.这充其量是次优的。 So what I am trying to achieve is some C# code that I can execute on a schedule.所以我想要实现的是一些我可以按计划执行的 C# 代码。

Using EPPlus, I have managed to load the excel file as a template, create a new one, get the data from SQL, update the 2 datasheets with the new data and then save the file.使用 EPPlus,我设法将 excel 文件加载为模板,创建一个新文件,从 SQL 获取数据,用新数据更新 2 个数据表,然后保存文件。

using (var templateStream = new MemoryStream(File.ReadAllBytes(@"PATH_TO_TEMPLATE_FILE")))
{
    using (var newStream = new MemoryStream())
    {
        //Create e NEW excel doc from the given template
        using (ExcelPackage excelPackage = new ExcelPackage(newStream, templateStream))
        {
            //load the data from SQL
            DataSet data = LoadDatasetFromQuery(configs, QueueItem);
            //loop over the DataTables inside the DataSet
            for (int i = 1; i <= data.Tables.Count; i++)
            {
                //Resolve the worksheet to put the data on
                var worksheetName = configs.FirstOrDefault(c => c.Name.StartsWith($"Worksheet.{i}."));
                ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[worksheetName.Value];
                //Put the data on the worksheet top/left = B3
                worksheet.Cells["B3"].LoadFromDataTable(data.Tables[i - 1], false);
            }
            //Save the file to the memory stream
            excelPackage.Save();
        }

        //Write the file to the file system
        File.WriteAllBytes(@"PATH_TO_OUTPUT_FILE", newStream.ToArray());
    }
}

The problem is, when I try and open the excel file, it says it is corrupt and tries to repair it, which is does, by removing the pivot tables completely.问题是,当我尝试打开 excel 文件时,它说它已损坏并尝试通过完全删除 pivot 表来修复它。 My template file makes use of named ranges as referred to in this SO post but that has not resolved the issue.我的模板文件使用了此 SO 帖子中提到的命名范围,但这并没有解决问题。

Herewith the excel log of how it completed the "repair" excel 日志记录了它是如何完成“修复”的

在此处输入图像描述

I have also dabbled a little bit in using the interop library ( Microsoft.Office.Interop.Excel ) but that is really like a black hole when it comes to debugging / documentation etc. I'm not averse to using it, I just don't know how.我还尝试过使用互操作库(Microsoft.Office.Interop.Excel),但在调试/文档等方面,这就像一个黑洞。我不反对使用它,我只是不不知道怎么做。 ( well nothing I have tried works properly anyways ) (好吧,无论如何我尝试过的都没有正常工作)

Any help with the above will be greatly appreciated.任何有关上述内容的帮助将不胜感激。 If you need more information, feel free to ask.如果您需要更多信息,请随时询问。

Ok, so it seems my above code was correct, but the excel template I was loading was dodgy.好的,看来我上面的代码是正确的,但是我正在加载的 excel 模板很狡猾。 In order to correct the issue I had to make sure that all the pivot tables used named ranges to refer to the data ( click anywhere on the pivot table, then click on the Formulas tab in the top ribbon and then click on Name Manager ) source and then use the offset calculation ( to enable a dynamic range ) as suggested in the link in my post above.为了纠正这个问题,我必须确保所有 pivot 表都使用命名范围来引用数据(单击 pivot 表上的任意位置,然后单击顶部功能区中的“公式”选项卡,然后单击“名称管理器”)源然后按照我上面帖子中的链接中的建议使用偏移计算(启用动态范围)。

=OFFSET(DataSource,$A$1,0,0:COUNTA(DataSource,$A:$A),COUNTA(DataSource!$1:$1)) =OFFSET(数据源,$A$1,0,0:COUNTA(数据源,$A:$A),COUNTA(数据源!$1:$1))

where DataSource = the name of the worksheet with the data其中 DataSource = 包含数据的工作表的名称

Finally, I set up the pivots to refresh their data on opening ( right click on the pivot table, go to data tab and tick the "refresh on open" option )最后,我设置了枢轴以在打开时刷新其数据(右键单击 pivot 表,go 到数据选项卡并勾选“打开时刷新”选项)

There is a bit of a pain in that when I open the generated doc it is in "Protected mode" so the data + calcs dont refresh, but if I just click "Enable Editing" it all updates and normal service is resumed, happy days!有点痛苦的是,当我打开生成的文档时,它处于“受保护模式”,因此数据+计算不会刷新,但是如果我只是单击“启用编辑”,它会全部更新并恢复正常服务,快乐的日子!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM