在复制行或范围时将图表的数据源更改为目标工作表
可能的使用场景
当您将包含图表的行或范围复制到新工作表时,图表的数据源不会更改。例如,如果图表的数据源为=Sheet1!$A$1:$B$4,则在将行或范围复制到新工作表后,数据源仍将保持不变,即=Sheet1!$A$1:$B$4。它仍然指向旧工作表即Sheet1。这也是Microsoft Excel中的行为。但是,如果您希望它指向新的目标工作表,则请使用CopyOptions.ReferToDestinationSheet属性,并在调用Cells.CopyRows()方法时将其设置为true。现在,如果您的目标工作表是DestSheet,则您的图表的数据源将从=Sheet1!$A$1:$B$4更改为=DestSheet!$A$1:$B$4。
复制行或区域时更改图表的数据源到目标工作表
以下示例代码解释了在将包含图表的行或范围复制到新工作表时使用CopyOptions.ReferToDestinationSheet属性的用法。该代码使用sample excel file并生成output excel file。
// 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); |