select a range of cell for apply styles

May 17, 2010 at 6:04 PM

Hello,

I want select a range of cell for apply styles(background color)

how i do that? i found CellRangeAddress, i don't know how use it.

Thank.

May 21, 2010 at 1:45 AM
Edited May 28, 2010 at 11:21 PM

If you want to apply the same style to a group of cells, I usually just create a single style and add it to the workbook and then add to each cell.  Here is an example.

// Get row to add style
HSSFRow row = sheet.GetRow(i);

// Pick font style settings to add to new style
HSSFFont rowCellFont = workbook.CreateFont();
rowCellFont.FontName = "Calibri";
rowCellFont.Color = HSSFColor.WHITE.index;

// Create a new style, set background color, assign font style (style is created in the workbook object)
HSSFCellStyle rowCellStyle = workbook.CreateCellStyle();
rowCellStyle.FillForegroundColor = HSSFColor.GREEN.index;
rowCellStyle.FillPattern = CellFillPattern.SOLID_FOREGROUND;
rowCellStyle.SetFont(rowCellFont);

// Apply style to Excel Cell 3 to Excel Cell 4
for(i=2; i <= 3; i++)
{
HSSFCell rowCell = row.GetCell(i);
rowCell.CellStyle = rowCellStyle;
}

I just typed a bunch of this by hand so hopefully no errors, but the idea should be clear.

May 28, 2010 at 6:28 PM

The expressions in for() statement should be delimited by semicolons, not commas:

      // Apply style to Excel Cell 3 to Excel Cell 4
      for (i = 2; i <= 3; i++)
      {
        HSSFCell rowCell = row.GetCell(i);
        rowCell.CellStyle = rowCellStyle;
      }

 

May 28, 2010 at 11:22 PM
good catch.. fixed in example above.
Jul 6, 2010 at 1:37 PM
Edited Jul 6, 2010 at 1:38 PM

I tried the ways mentioned above but when we exceed a certain number of times of applying the style in the program and when opening the excel It gives the following error:

Some text formatting may have been changed in this file because the maximum number of fonts was exceeded.