The MindFusion Forums
Grid and Spreadsheet Components >> WPF >> Copy merged cells
https://mindfusion.eu/Forum/YaBB.pl?num=1470900227

Message started by sm.eagle on Aug 11th, 2016 at 7:23am

Title: Copy merged cells
Post by sm.eagle on Aug 11th, 2016 at 7:23am
It's me again,

Continuing from the last topic, I noticed that merged cells are not transferred when copy/pasting worksheet content. How can I remedy that?

Cheers,
Sam

Title: Re: Copy merged cells
Post by Meppy on Aug 11th, 2016 at 10:55am
Hi,

You need to copy and paste the merged cell data manually. For this purpose, define a new MergedCellData class, tagged as [Serializable], which will hold the merged cell information:


Code (][Serializable):

class MergedCellData
{
     public MergedCellData(List<string> mergedCells, int left, int top)
     {
           MergedCells = mergedCells;
           OriginLeft = left;
           OriginTop = top;
     }

     public List<string> MergedCells
     {
           get;
           private set;
     }

     public int OriginLeft
     {
           get;
           private set;
     }

     public int OriginTop
     {
           get;
           private set;
     }
}

Note that, along with the merged cell ranges, the class also contains the top/left of the selection range. This is done so that the merged cell ranges can be offset appropriately when pasted.

Now, in the Copy method, collect all merged cell ranges within the selection in the active worksheet:


Code (]var mergedCells = activeSheet.MergedCells.Where(mergedCell => Contains(selectionRange, mergedCell))
     .Select(mergedCell => mergedCell.ToString()).ToList();
var mergedCellData = new MergedCellData(mergedCells, selectionRange.Left, selectionRange.Top);
dataObject.SetData(mergedCellData);[/code):


The Contains method above checks whether a cell range is completely contained in another cell range. Inside the Paste method, check if the clipboard contains merged cell data and restore it by offsetting the cell ranges accordingly:

[code]if (dataObject.GetDataPresent(typeof(MergedCellData)))
{
     var mergedCellData = (MergedCellData)dataObject.GetData(typeof(MergedCellData));

     foreach (var mergedCell in mergedCellData.MergedCells)
     {
           var range = activeSheet.CellRanges[mergedCell];
           range = activeSheet.CellRanges[
                 range.Left + workbookView.Selection.Left - mergedCellData.OriginLeft,
                 range.Top + workbookView.Selection.Top - mergedCellData.OriginTop,
                 range.Right + workbookView.Selection.Left - mergedCellData.OriginLeft,
                 range.Bottom + workbookView.Selection.Top - mergedCellData.OriginTop];
           range.Merge();
     }
}

Let me know if this helps.

Regards,
Meppy

The MindFusion Forums » Powered by YaBB 2.6.11!
YaBB Forum Software © 2000-2024. All Rights Reserved.