复制行或范围时将图表的数据源更改为目标工作表

可能的使用场景

当您将包含图表的行或范围复制到新工作表时,图表的数据源不会更改。例如,如果图表的数据源为=Sheet1!$A$1:$B$4,则将行或范围复制到新工作表后,数据源将保持不变,即=Sheet1!$A$1:$B$4。它仍然指的是旧工作表,即 Sheet1。这也是 Microsoft Excel 中的行为。但是如果你想让它引用新的目标工作表,那么请使用复制选项.ReferToDestinationSheet属性并将其设置为真的同时调用Cells.CopyRows()方法。现在,如果您的目标工作表是 DestSheet,则图表的数据源将从 =Sheet1!$A$1:$B$4 更改为 =DestSheet!$A$1:$B$4。

复制行或范围时将图表的数据源更改为目标工作表

下面的示例代码解释了复制选项.ReferToDestinationSheet将包含图表的行或范围复制到新工作表时的属性。该代码使用示例 excel 文件并生成输出excel文件.

待办事项:图片_替代_文本

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Load sample excel file
Workbook wb = new Workbook(dataDir + "sample.xlsx");
// Access the first sheet which contains chart
Worksheet source = wb.Worksheets[0];
// Add another sheet named DestSheet
Worksheet destination = wb.Worksheets.Add("DestSheet");
// Set CopyOptions.ReferToDestinationSheet to true
CopyOptions options = new CopyOptions();
options.ReferToDestinationSheet = true;
// Copy all the rows of source worksheet to destination worksheet which includes chart as well
// The chart data source will now refer to DestSheet
destination.Cells.CopyRows(source.Cells, 0, 0, source.Cells.MaxDisplayRange.RowCount, options);
// Save workbook in xlsx format
wb.Save(dataDir + "output_out.xlsx", SaveFormat.Xlsx);