How to put the background color in the cells of the first line using NPOI?

2

I'm using the NPOI library to be able to generate an Excel file.

This is the first time I've been in touch with this library and would like help putting background color on the cells in the first row.

My current code is this:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;

namespace Excel
{
    class Program
    {
        static void Main(string[] args)
        {

            var wb = new HSSFWorkbook();

            var sheet = wb.CreateSheet("Model");

            var header = sheet.CreateRow(0);

            header.CreateCell(0).SetCellValue("Title");

            header.CreateCell(1).SetCellValue("Text");

            string filename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".xls");

            using (var stream = File.Open(filename, FileMode.Create))
            {
                wb.Write(stream);
            }
        }

    }
}
    
asked by anonymous 20.07.2017 / 14:33

1 answer

2

Create a new style , set the FillPattern properties to FillPatternType.SOLID_FOREGROUND and FillForegroundColor with the color you want. / p>

Then define this style as CellStyle of header cells.

See an example:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;


namespace Excel
{
    class Program
    {
        static void Main(string[] args)
        {    
            var wb = new HSSFWorkbook();    
            var sheet = wb.CreateSheet("Model");    
            var header = sheet.CreateRow(0);

            ICellStyle hStyle = wb.CreateCellStyle();
            hStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Precent.index;
            hStyle.FillPattern = FillPatternType.SolidForeground;


            var cell0 = header.CreateCell(0);    
            cell0.SetCellValue("Title");
            cell0.CellStyle = hStyle;

            var cell1 = header.CreateCell(1)
            cell1.SetCellValue("Text");
            cell1.CellStyle = hStyle;

            string filename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".xls");

            using (var stream = File.Open(filename, FileMode.Create))
            {
                wb.Write(stream);
            }
        }

    }
}
    
20.07.2017 / 14:46