C# Excel VSTO - Possible to move a pivottable?

女生的网名这么多〃 提交于 2019-12-24 01:25:43

问题


I am trying to move a PivotTable in VSTO and not succeeding at all. My logic was to find the range of the pivot table, cut it and paste it into a new range where i am sure that no data exists on the worksheet.

    public static void MovePivotTable(string sheetName, PivotTable pivotTable, int newX, int newY, int width, int height)
    {
        try
        {
            Worksheet worksheet = GetOrCreateWorksheet(sheetName);

            Range topLeft = (Range)worksheet.Cells[newX, newY];
            Range bottomRight = (Range)worksheet.Cells[newX + width, newY + height];
            Range newRange = worksheet.get_Range(topLeft, bottomRight);

            pivotTable.TableRange1.Cut(Missing.Value);

            newRange.PasteSpecial(XlPasteType.xlPasteAll, XlPasteSpecialOperation.xlPasteSpecialOperationNone,
                Missing.Value, Missing.Value);

            return;
        }
        catch (Exception)
        {
        }
        finally
        {
        }
    }

However I always get an exception. Either: - PasteSpecial has failed. - Something along the lines that it is impossible to modify a pivot table.

Has anyone ever done this? Can they confirm that this is indeed possible or not? Any sample code?

Many thanks, Sean


回答1:


Two things:

TableRange1 doesn't include the Pivot Table's header, so that's why you're getting the "Can't Modify" error. Use TableRange2 to select the whole Pivot Table.

Also, you can't do a PasteSpecial on a Cut, so just use the Destination argument of the Cut method. This is how it would look in VB:

pivotTable.TableRange2.Cut Destination:=NewRange


来源:https://stackoverflow.com/questions/8564738/c-sharp-excel-vsto-possible-to-move-a-pivottable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!