Nathan
Nathan

Reputation: 919

NPOI create cell containing bold and non bold text

I'm using NPOI to output excel from Asp.Net MVC app and works very well with plain text but have now been requested to add formatting and am having problems where I need to have a single cell with bold text followed by non-bold text. e.g.

This text bold - this text normal

I know I can give a cell a single style but this won't help and I cannot see anyway to give a cell some pre-formatted rich text.

The only possible solution that I can think of is creating two cells separately and the merge them together but will that then mean the formatting will be lost?

Is there a way to do this that I have missed in NPOI?

Upvotes: 29

Views: 40830

Answers (5)

Ernie Banzon
Ernie Banzon

Reputation: 355

You may try this:

        var font = reportWorkbook.CreateFont();
        font.FontHeightInPoints = 11;
        font.FontName = "Calibri";
        font.IsBold = true; 

        var cell = headerRow.CreateCell(0);
        cell.SetCellValue("Test Bold");
        cell.CellStyle = reportWorkbook.CreateCellStyle();
        cell.CellStyle.SetFont(font);

Upvotes: 33

kumar chandraketu
kumar chandraketu

Reputation: 2370

Use this option

 font.Boldweight = (short)700;//FontBoldWeight.Bold;

Actual syntax should be like below. But both of these syntax doesn't works sometime

font.Boldweight = FontBoldWeight.Bold ;  
Or 
font.Boldweight = (short)FontBoldWeight.Bold; 

FontBoldWeight is type enum, which after type casting may not work sometime. As a workaround if you type caste or use actual short value of enum directly, it works. Below is the declaration of FontBoldWeight. it will make things clear.

**public enum FontBoldWeight
    {
              None = 0,
              Normal = 400,
              Bold = 700,
    }**

Upvotes: 2

oPless
oPless

Reputation: 645

Seems that the Ernie Banzon answer no longer works exactly as described, possibly due to a namespace change (or in fact that I'm using the HSSF namespace?)

// usings
using NPOI.HSSF.UserModel;

// IWorkbook doc
IFont font = doc.CreateFont();
font.FontHeightInPoints = 11;
font.FontName = "Arial";
font.Boldweight = (short)FontBoldWeight.BOLD;

Upvotes: 7

Tarek El-Assady
Tarek El-Assady

Reputation: 311

Fortunately, you able to do that... Look at this code:

Font f1=wb.CreateFont();
f1.Color=HSSFColor.RED.index;
ws.GetRow(1).GetCell(0).RichStringCellValue.ApplyFont(1, 5, f1);

Upvotes: 31

Nathan
Nathan

Reputation: 919

After a fair amount of investigation it seems that you are not able to do this inside of NPOI as it doesn't provide the necessary functionality to allow you to set formatting on specific text within a cell like I was attempting to do.

Upvotes: -1

Related Questions