Set Multiple styles in a single excel cell using OfficeOpenXml in C# - c#

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: "ABCD"
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);

Related

How to copy worksheet data and style with EPPlus C#?

I am saving data to a new worksheet with EPPlus. But it doesn't copy the styles of the worksheet I use as a template. How can I do that?
As seen in the picture, the cell height of the template is 25, while the cell height of the new worksheet I created using the template is 18. I want the cell height in the new worksheet to be 25 as well.
My code is here..
FileInfo template = new FileInfo(path + #"\Template\template.xlsx");
using (ExcelPackage package = new ExcelPackage(template))
{
FileInfo newFile = new FileInfo(fileCheck);
using(ExcelPackage pack = new ExcelPackage(newFile))
{
ExcelWorksheet ws0 = package.Workbook.Worksheets[0];
ws0.Cells["A8"].Value = texedit2.Text;
pack.Workbook.Worksheets.Add("Sheet2", ws0);
pack.SaveAs(newFile);
}
}
Is there any other solution?
The best way I've found to do this loop through each row in the new worksheet and manually set the height to match the corresponding row in the template.
ExcelWorksheet ws0 = package.Worksheets[0];
ExcelWorksheet newWorksheet = pack.Workbook.Worksheets.Add("Sheet2", templateWorksheet);
for(int i = 0; i < ws0.Dimensions.Row + 1; i++)
{
newWorksheet.Rows[i].CustomHeight = true;
newWorksheet.Rows[i].Height = ws0.Rows[i].Height;
}

NPOI: change font color of some (not all) text in cell

When using C# NPOI, is there a way to change the font color of only some of the text within a cell? I know you can change the font color for the entire cell. But I would like to only change the color of the last 4 character in that cell.
I know there is a way to do this in VBA:
However, I do not see a way to do the same thing using NPOI
Example for DotNetCore.NPOI:
var newFile = #"newbook.core.xlsx";
using (var fs = new FileStream(newFile, FileMode.Create, FileAccess.Write))
{
var workbook = new XSSFWorkbook();
var sheet = workbook.CreateSheet("Sheet1");
var rowIndex = 0;
var row = sheet.CreateRow(rowIndex);
var cell = row.CreateCell(0);
var text = "this is content";
cell.SetCellValue(text);
var font = workbook.CreateFont();
font.Color = HSSFColor.Blue.Index2;
cell.RichStringCellValue.ApplyFont(text.Length - 4, text.Length, font);
workbook.Write(fs);
}
The code also works for .NET framework and NPOI nuget package.
Result:
Cell has property RichStringCellValue. You can call ApplyFont method on RichStringCellValue and specify the range where the font will be applied.

open xml, set cellvalue html string

Technologies: C#, openxml
I am trying to create xlsx file using opennxml document. Data table contains one column with rich text in html string. example "hi" or hi
How to append/set value to cellValue.Text. Please suggest any other approach to achieve this.
Cell cell = new Cell() { CellReference = ExcelHelper.ColumnCaption.Instance.Get((Convert.ToInt32((UInt32)rowIndex) - 2), cIndex), DataType = CellValues.InlineString };
cell.DataType = new EnumValue<CellValues>(CellValues.String);
CellValue cellValue = new CellValue();
cellValue.Text = data.Rows[rIndex][cIndex].ToString();//<b>hi</b>
cell.Append(cellValue);

Create Excel file with style tag using OpenXmlWriter SAX

I am trying to write an Excel Xlsx spreadsheet with styling using OpenXmlWriter (SAX).
I am able to create the file with rows and columns (populate them as strings).
I am looking for a simple code on how to make the first row (header) with bold font.
I do not have a template file to start with as the file will be dynamic.
I found a few articles on how to add WorkbookStylesPart, but they are all using the DOM. As i need to write large number of rows, the DOM will not work for me.
Could anyone point me at the right direction?
Simple code to add a header row as bold when using WriteStartElement and OpenXmlAttribute.
Thanks, odansky
Adding StyleSheet is one time work. After that you just need to simply refer the defined style ID when creating new cells.
Hot to add a stylesheet to spreadsheet [With Bold text style]
private WorkbookStylesPart AddStyleSheet(SpreadsheetDocument spreadsheet)
{
WorkbookStylesPart stylesheet = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
Stylesheet workbookstylesheet = new Stylesheet();
Font font0 = new Font(); // Default font
Font font1 = new Font(); // Bold font
Bold bold = new Bold();
font1.Append(bold);
Fonts fonts = new Fonts(); // <APENDING Fonts>
fonts.Append(font0);
fonts.Append(font1);
// <Fills>
Fill fill0 = new Fill(); // Default fill
Fills fills = new Fills(); // <APENDING Fills>
fills.Append(fill0);
// <Borders>
Border border0 = new Border(); // Defualt border
Borders borders = new Borders(); // <APENDING Borders>
borders.Append(border0);
// <CellFormats>
CellFormat cellformat0 = new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 }; // Default style : Mandatory | Style ID =0
CellFormat cellformat1 = new CellFormat() { FontId = 1 }; // Style with Bold text ; Style ID = 1
// <APENDING CellFormats>
CellFormats cellformats = new CellFormats();
cellformats.Append(cellformat0);
cellformats.Append(cellformat1);
// Append FONTS, FILLS , BORDERS & CellFormats to stylesheet <Preserve the ORDER>
workbookstylesheet.Append(fonts);
workbookstylesheet.Append(fills);
workbookstylesheet.Append(borders);
workbookstylesheet.Append(cellformats);
// Finalize
stylesheet.Stylesheet = workbookstylesheet;
stylesheet.Stylesheet.Save();
return stylesheet;
}
Now when you create a cell do following to refer to the Bold text
Cell c1 = new Cell(){StyleIndex = Convert.ToUInt32(1)}; // Assign our defined style with Bold text ; Style ID 1
Additional Note : You need to add stylesheet after adding workbookpart of the spreadsheet.
More regarding SAX approach : You can define styles when you first create the template file which you gonna open to insert data cells. And when adding data cells refer to the defined styles using ID.
A simple working spreadsheet with style (MSDN)
public static void CreateSpreadsheetWorkbook(string filepath)
{
// Create a spreadsheet document by supplying the filepath.
// By default, AutoSave = true, Editable = true, and Type = xlsx.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
AddStyleSheet(spreadsheetDocument) // <== Adding stylesheet using above function
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
sheets.Append(sheet);
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}
You set the style index the same way you set the datatype for the cell:
oxa.Add(new OpenXmlAttribute("s", null, "1"));

How to get value shown in cell from .xlsx using open XML C#

Im new to C# and open XML, so please be patient with my ingnorance.
I have this problem:
I need to get cell value from .xlsx file. I can do that using XlGetCellValue method.
But When one cell (for example A2 from sheet1) gets it value from another cell (B2 sheet2)
XlGetCellValue("", "Sheet1", "A2")
returns Sheet2!B2Joe.
Or when the cell contains computation (like =C2+D2), XlGetCellValue(...) returns C2+D2120
Is there any easy way to get just value "Joe" and "120?
Here the link to MSDN on how to get the value of a cell using the Open XML SDK 2.5. There is a code sample provided.
How to: Retrieve the values of cells in a spreadsheet document (Open XML SDK)
Working with openxmnl could be a pain in the ass if you haven't yet downloaded OpenXMLSDKToolV25.msi (Productivity tool).
basically it's a reflection tool. you can open an excel document and the tool create all code you need to build the same from scratch.
CellValue it's only for value. using formula you have to deal with cell formula.
Eg. I created an excel file in A1 = 1256 in B1 = 2 in C1 "=A1*B1"
Opening the file with OpenXMLSDKTool i got:
public Row GenerateRow()
{
Row row1 = new Row(){ RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:3" } };
Cell cell1 = new Cell(){ CellReference = "A1" };
CellValue cellValue1 = new CellValue();
cellValue1.Text = "1256";
cell1.Append(cellValue1);
Cell cell2 = new Cell(){ CellReference = "B1" };
CellValue cellValue2 = new CellValue();
cellValue2.Text = "2";
cell2.Append(cellValue2);
Cell cell3 = new Cell(){ CellReference = "C1" };
CellFormula cellFormula1 = new CellFormula();
cellFormula1.Text = "A1*B1";
CellValue cellValue3 = new CellValue();
cellValue3.Text = "2512";
cell3.Append(cellFormula1);
cell3.Append(cellValue3);
row1.Append(cell1);
row1.Append(cell2);
row1.Append(cell3);
return row1;
}
from this you can notice that CellValue and CellFormula are both childs of Cell.
So, assuming you can retrieve your Row r you can have this:
Cell c = r.Elements<Cell>().ElementAt(2);
CellValue cv = c.CellValue;
CellFormula cf = c.CellFormula;

Categories