Page Index Toggle Pages: 1 Send TopicPrint
Normal Topic Copy merged cells (Read 2368 times)
sm.eagle
YaBB Newbies
*
Offline


I Love MindFusion!

Posts: 4
Joined: Aug 2nd, 2016
Copy merged cells
Aug 11th, 2016 at 7:23am
Print Post  
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
  
Back to top
 
IP Logged
 
Meppy
God Member
*****
Offline


MindFusion support

Posts: 1783
Joined: Jul 20th, 2005
Re: Copy merged cells
Reply #1 - Aug 11th, 2016 at 10:55am
Print Post  
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
Select All
[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
Select All
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); 


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
Select All
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
  
Back to top
 
IP Logged
 
Page Index Toggle Pages: 1
Send TopicPrint