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

可能的使用场景

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

复制行或区域时更改图表的数据源到目标工作表

以下示例代码解释了在将包含图表的行或范围复制到新工作表时使用CopyOptions.ReferToDestinationSheet属性。该代码使用示例Excel文件并生成输出Excel文件。屏幕截图显示了输出Excel文件中图表的数据源现在指向DestSheet而不是Sheet1。

todo:image_alt_text

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(ChangeDataSource.class);
// Load sample excel file
Workbook wb = new Workbook(dataDir + "sample.xlsx");
// Access the first sheet which contains chart
Worksheet source = wb.getWorksheets().get(0);
// Add another sheet named DestSheet
Worksheet destination = wb.getWorksheets().add("DestSheet");
// Set CopyOptions.ReferToDestinationSheet to true
CopyOptions options = new CopyOptions();
options.setReferToDestinationSheet(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.getCells().copyRows(source.getCells(), 0, 0, source.getCells().getMaxDisplayRange().getRowCount(),
options);
// Save workbook in xlsx format
wb.save(dataDir + "output.xlsx", SaveFormat.XLSX);