I have a requirement where i need to assign a font style to a range of cells instead of cell by cell. Also, the cell range is dynamic as the same program is used for multiple reports so could not use cell by cell. Could you please suggest.
Cells cells = xlwkst.Cells;
Range range = cells.CreateRange(ccol1, ccol2);
Need to apply formatting for the above cells.
Also, if i use the below logic, the Bold Format is getting applied to entire cell but i need only for the text inside the cell and the borders of the cell should not change.
See the following sample code for your reference then write/update your code accordingly
e.g. Sample code:
// Load sample Excel file containing cells with formatting.
Workbook wb = new Workbook("Book1.xlsx");
// Access first worksheet.
Worksheet ws = wb.Worksheets[0];
// Create cells range.
Range rng = ws.Cells.CreateRange("B2:D7");
// Create style object.
Style st = wb.CreateStyle();
// Set the horizontal and vertical alignment to center.
st.HorizontalAlignment = TextAlignmentType.Left;
st.VerticalAlignment = TextAlignmentType.Center;
// Set font style.
// Change font name and size (if required)
st.Font.Name = "Calibri";
st.Font.Size = 9;
// Set Normal Style
st.Font.IsBold = false;
// Create style flag object.
StyleFlag flag = new StyleFlag();
// Set style flag options (which you specified above), i.e., alignments, Font(name, size, bold(off)) to true. It is most crucial statement.
// Because if it will be false, no changes will take place.
flag.Alignments = true;
flag.FontName = true;
flag.FontSize = true;
flag.FontBold = true;
// Apply style to range of cells.
rng.ApplyStyle(st, flag);
// Save the workbook in XLSX format.
wb.Save("outputChangeCellsAlignmentAndFontStyle_with_KeepExistingFormatting.xlsx", SaveFormat.Xlsx);
Let us know if you still find any issue or confusion.
Since a range involves multiple cells with each cell might have different formatting/styles, so you cannot get formatting via your desired (single) API (Range.GetStyle()) as a whole. There is no GetStyle method for Range object. But there is SetStyle() method (overloads) of Range.