We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

How to Copy just the style object from Range?

Hi,

Just assume we have a Range object with an existing style say Bold=true and now if i want to assign one more style(Italic=true) without losing the previous existing style, how do i do that?

I noticed Range object has copystyle() method where we can copy style from one to another , but doesn’t gives its style object
Ex:

// local variable
Range cellRange;

public void Method1()
{
CellsFactory cellsFactory = new CellsFactory();
Style style = cellsFactory.CreateStyle();
style.Font.IsBold = true;
cellRange.ApplyStyle(style, new StyleFlag() { All = true });
}

public void Method2()
{  
   CellsFactory cellsFactory = new CellsFactory();
   Style style = cellsFactory.CreateStyle();
   style.Font.IsItalic = true;
  // This overwrites previous style, how do i prevent the existing styles and apply new ones?
   cellRange.ApplyStyle(style, new StyleFlag() { All = true });
}

@PrathapSV,

Well, Range.CopyStyle() does not suit for your scenario/ case, it only copies formatting from a source range to destination range. Seeing your sample line of code, i.e.,
e.g
Sample code:

CellsFactory cellsFactory = new CellsFactory();
Style style = cellsFactory.CreateStyle();

this will create new style in the workbook having all the attributes as null. So, whatever formattings your apply (e.g style.Font.IsItalic = true) it will override the previous one. To cope with it, you got to create the style with respective to previous style or you may get the style/formatting of any cell (in the range) to instantiate the new one. Suppose your existing range (A1:A10) has existing style/formattings, e.g bold font, etc. Now you will create new style by obtaining the style of a cell, e.g A1 cell (in the range) and then specify your additional formatting attributes (e.g italic font, etc.) and then specify relevant style flag attribute. Finally apply the range style to it, see the sample code for your reference:
e.g
Sample code:

........

public void Method2()
{  
........
   Style style = cell.getStyle();
   style.Font.IsItalic = true;
   cellRange.ApplyStyle(style, new StyleFlag() { FontItalic = true });
}
.........

Hope, this helps a bit.