I cannot find a way to style a single excel cell in different styles. For example I need to make only some part of the string bold and leave the rest unbold in one cell. I can only access Cells not characters in OpenXml.
Usually what I do to style the cell is,
ExcelPackage package = new ExcelPackage();
ExcelWorksheet ws = package.Workbook.Worksheets.Add("SheetName");
ws.Cells[1, 1].Style.Font.Bold = true;
I can't find a way to access characters in a cell. I saw some other excel plugins do the same but Is there any way OpenXml can do this? Any suggestions will be great. Thanks
The answer here works well.
You have to add the cell content as separate ExcelRichText objects.
Example:
ExcelRichText rt1 = ws.Cells[1, 1].RichText.Add("AB");
rt1.Bold = true; // bold just the "AB"
ExcelRichText rt2 = ws.Cells[1, 1].RichText.Add("CD");
Output will be: " AB CD"
Note: You will need to reference the namespace OfficeOpenXml.Style
This is how you can add partial styles in an excel sheet using OpenXML.
//Partial Cell Styling
uint currentRow = 2;
Row newRow = new Row() { RowIndex = currentRow };
//create a new inline string cell
Cell cell = new Cell() { CellReference = "J" + currentRow.ToString() };
cell.DataType = CellValues.InlineString;
//create a run for the bold text
Run run1 = new Run();
run1.Append(new Text("By: "));
//create a second run for the non-bod text
Run run2 = new Run();
run2.Append(new Text(Environment.NewLine + " SAHIL VIG") { Space = SpaceProcessingModeValues.Preserve });
//create runproperties and append a "Bold" to them
RunProperties run2Properties = new RunProperties();
run2Properties.Append(new Bold());
//set the first runs RunProperties to the RunProperties containing the bold
run2.RunProperties = run2Properties;
//create a new inline string and append both runs
InlineString inlineString = new InlineString();
inlineString.Append(run1);
inlineString.Append(run2);
//append the inlineString to the cell.
cell.Append(inlineString);
//append the cell to the row
newRow.Append(cell);
sheetData.Append(newRow);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.