Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 530
Nathan Avatar asked May 09 '11 09:05

Nathan


4 Answers

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);
like image 138
Tarek El-Assady Avatar answered May 19 '23 21:05

Tarek El-Assady


You may try this:

        var font = reportWorkbook.CreateFont();
        font.FontHeightInPoints = 11;
        font.FontName = "Calibri";
        font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD; 

        var cell = headerRow.CreateCell(0);
        cell.SetCellValue("Test Bold");
        cell.CellStyle = reportWorkbook.CreateCellStyle();
        cell.CellStyle.SetFont(font);
like image 29
Ernie Banzon Avatar answered May 19 '23 21:05

Ernie Banzon


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;
like image 37
oPless Avatar answered May 19 '23 22:05

oPless


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,
    }**
like image 40
kumar chandraketu Avatar answered May 19 '23 20:05

kumar chandraketu