问题
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