Quantcast
Channel: ClosedXML - The easy way to OpenXML
Viewing all articles
Browse latest Browse all 1877

Commented Unassigned: WorkSheet CopyTo doesn't transform Named Ranges addresses [9270]

$
0
0
I'm trying to replicate a Worksheet several time in a Workbook and I'm doing using the following code:
```
IXLWorksheet worksheet = modelSheet.CopyTo("SheetName");
```
When I open the generated document the NamedRanges were copied, using the same name as expected, but all of them are associated to the model worksheet (source). I was expecting the NamedRange address to be changed to the target Worksheet too.

Example:
```
"=ModelSheet!$B$10:$B$10" would transform to "=TargetSheet!$B$10:$B$10"
```

Is there a way to do it or isn't it supported yet?

Many Thanks & great work my man, incredible Lib!
Cheers!
Comments: ** Comment from web user: Rynkadink **

Meanwhile... I did create an Extension Method as a workaround;
It might be usefull to someone else:

```
public static class ClosedXml
{
public static IXLWorksheet CopyToWithNamedRanges(this IXLWorksheet sourceSheet, String targetSheetName)
{
if (sourceSheet == null)
{
throw new ArgumentNullException("Source Worksheet is Null!");
}

// # Call ClosedXML API CopyTo method

IXLWorksheet targetWorksheet = sourceSheet.CopyTo(sourceSheet.Workbook, targetSheetName);

// # Process copied Worksheet NamedRanges,
// Change Address reference replacing the source Worksheet name with newly created
// Worksheet (by copy) name.

foreach (IXLNamedRange namedRange in targetWorksheet.NamedRanges.Select(r => r))
{
// Get the source worksheet name from address

string[] splitAddress = namedRange.RefersTo.Split(new char[] { '!' }, 2);

string worksheetName = splitAddress[0];

// Enclose the target worksheet name in single quotes

string targetWorksheetName = String.Format("'{0}'", targetWorksheet.Name);

// Change the range reference address

namedRange.RefersTo = namedRange.RefersTo.Replace(worksheetName, targetWorksheetName);
}

return targetWorksheet;
}
}
```


Viewing all articles
Browse latest Browse all 1877

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>