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

Asked

Viewed 360 times

2

I am using the NPOI library to generate an Excel file.

It is the first time I am having contact with this library and would like help to put background color in the cells of the first line.

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);
            }
        }

    }
}

1 answer

2


Create a new style, define the properties FillPattern as FillPatternType.SOLID_FOREGROUND and FillForegroundColor with the color you want.

Then set this style as CellStyle of the cells of header.

Take 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);
            }
        }

    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.