This project has moved and is read-only. For the latest updates, please go here.

How to bold specific text inside a cell and delete some html tags after bolding

Sep 9, 2013 at 5:06 AM

Can I ask how can i bold a specific text inside a cell? i know that it can be accomplish by
            var workbook = new XLWorkbook();
            var worksheet = workbook.Worksheets.Add("Sample Sheet");
            worksheet.Cell("A1").Value = "<b>test</b>" + System.Environment.NewLine + "test1";
            worksheet.Cell("A1").RichText.Substring(3, 4).SetBold(true);
as what you can see my cell value contains html tags and i can set "test" as bold using substring as per the documentation states. my problem is i needed to delete the <b> tags right after i bold the "test" string. i tried
worksheet.Cell("A1").RichText.Substring(3, 4).SetBold(true).ToString().Remove(1,2);


worksheet.Cell("A1").Value=worksheet.Cell("A1").RichText.Substring(3,4).SetBold(true).ToString().Remove(1, 2);
but doesnt work. can someone help me pls.

Sep 9, 2013 at 5:37 AM
Pick up the latest source code and use the following:
        var wb = new XLWorkbook();
        var ws = wb.AddWorksheet("Sheet");
        ws.FirstCell().Value = "<b>test</b>" + System.Environment.NewLine + "test1";
        ws.FirstCell().RichText.Substring(3, 4).SetBold();
        ws.FirstCell().RichText.ForEach(richString => richString.Text = richString.Text.Replace("<b>", "").Replace("</b>", ""));
The problem is that when you change the formatting of a rich text, Excel splits the string into multiple "runs" (each with its own formatting). If you want to modify the text then you have to go through each rich string inside the RichText and modify it independently.

To make it clearer put a breakpoint after the .SetBold() and inspect the RichText. You'll see that it's now a collection of rich strings and it has 3 items. The second one is in bold.

Sep 9, 2013 at 5:48 AM
Wow this is great! Your solution is clean and you replied so fast. Yes i also breakpoint and saw that it was chop into bits but im not that good in linq thats why i posted.

Thank you very much MDeleon. Ill try this one out.
Sep 9, 2013 at 5:53 AM
Btw i got an error "Property or indexer CLosexml.excel.ixlrichstring.text cannot be assigned because its readonly.

im using

ClosedXML for .Net Framework 4.0 (ClosedXML 0.69.1)
in the downloads page

Am i missing something?

Sep 11, 2013 at 8:28 AM
bump. could anyone help pls
Sep 11, 2013 at 2:10 PM
Get the latest source code. This hasn't been released yet.
Sep 11, 2013 at 2:59 PM
i see so i have to change the code by myself.. I hope youll release the version who has that issue patch.

anyway. thanks for the library it woks great. keep it up!
Sep 11, 2013 at 3:54 PM
You don't have to change the code. Just download the source code, open it in Visual Studio and build it. No change required.