Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClosedXML predefined style

Tags:

c#

closedxml

Is it possible to create and store predefined style in ClosedXML, so I can apply it to a certain range later?Just like Excel can. For example by a static class:

public static class ReportStyle
{ 
    public static XLStyle Default {
        get {
           XLStyle style = new XLStyle(); //or something like that, I want a different XLStyle object
           style.Font. //etc, all the changes
           return style;
        }
    }
}

And later I would want to do something like:

range.Style = ReportStyle.Default;

I want to predefine some of them, because each one can be used many times in different parts of document, for example in different sheets. Right now I created a crude workaround being a methods hidden under delegates, so I can store them for my modules (too much to explain - I just need to store style as object - because I need ability to copy it):

public delegate bool StyleDelegate(IXLRange range);

And then I can store my style-changing-method inside, and invoke it some time later during style applying phase:

public static void SetStyleDefault(IXLRange range){
    //do some style changes for this range
}

public StyleDelegate Style { get; set; } = ReportStyle.SetStyleDefault;

It works and it's some way to do this, but I find it rather complicated and a little counter intuitive for future users and it would be best, to just store some different static XLStyle object and apply it to certain ranges, that I want to have this style.

I want to create some kind of "framework" that will be used to simplify xlsx documents creation (having ready-to-use, predefined blocks that can be later used as puzzles) - so I want to keep it simple and intuitive to use.

like image 955
Khaine Avatar asked Mar 16 '26 08:03

Khaine


1 Answers

I cannot say for sure for versions prior to 0.93 (that's when the question was posted), but in 0.93 the styles managing was redesigned in order to reduce the memory consumption and now it is definitely possible.

Take a default style, tweak it in a desired way and store wherever you like: in a variable, in a static field, or in a dictionary:

var myCustomStyle = XLWorkbook.DefaultStyle;
myCustomStyle.Fill.SetBackgroundColor(XLColor.Red);
myCustomStyle.Font.SetBold(true);
myCustomStyle.Font.SetFontSize(20);

After that you are free to use this style in any workbook you want:

using (var wb = new XLWorkbook())
{
    var ws = wb.AddWorksheet();
    ws.Range("A1:A3").Style = myCustomStyle;
    wb.SaveAs(...);
}

Voila!

enter image description here

like image 127
Aleksei Avatar answered Mar 18 '26 20:03

Aleksei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!