Reputation: 335
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.
Upvotes: 3
Views: 7017
Reputation: 591
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!
Upvotes: 8
Reputation: 41
I use reflection to create empty style. It's not good to use such thing but it's better than nothing
static IXLStyle CreateEmptyStyle()
{
var t = typeof(ClosedXML.Excel.XLConstants).Assembly.GetType("ClosedXML.Excel.XLStyle");
MethodInfo m = t?.GetMethod("CreateEmptyStyle", BindingFlags.Static | BindingFlags.NonPublic);
var o = m?.Invoke(null, null);
return o as IXLStyle;
}
Upvotes: 1