Search code examples
c#fontsnpoiitalic

How can I specify font as 'Italic' using NPOI 2.2.1.0?


I want to create my own style for cell in Ecxel document. I need cell text to be displayed as 'Italic' like this 'blablabla'. How can I do it? I tried something like this:

wb = new XSSFWorkbook(stream);
var font = wb.CreateFont();
font.SetItalic(true)

but there is no 'SetItalic' method in NPOI API, just readoly 'IsItalic' property.


Solution

  • According to the documentation, IsItalic is a read/write property.

    Here is a little code sample demonstrating how to apply an italic font to a particular cell:

    var wb = new XSSFWorkbook();
    var sheet = wb.CreateSheet("Sheet 1");
    
    // Create an italic font
    var font = wb.CreateFont();
    font.IsItalic = true;
    
    // Create a dedicated cell style using that font 
    var style = wb.CreateCellStyle();
    style.SetFont(font);
    
    var row = sheet.CreateRow(0);
    
    row.CreateCell(0).SetCellValue("Username");
    
    var cell = row.CreateCell(1);
    cell.SetCellValue("Email");
    // Apply the cellstyle we craeted
    cell.CellStyle = style;
    
    using (var fileData = new FileStream(@"G:\scratch\sheet2.xlsx", FileMode.Create))
    {
      wb.Write(fileData);
    }