13

Can anybody help me with ExcelLibrary? I'd like to set a cell background and font color, but I don't know how can I do it. I try to get access to a cell style, but I didn't found it.

Anybody have any ideas?

misho
  • 1,195
  • 6
  • 16
  • 29
  • 2
    Is it important that you use ExcelLibrary? You might check out NPOI as an alternative, I am not too familiar with ExcelLibrary but NPOI is probably going to be more feature rich and this is pretty simple to do. – Jamie Treworgy Feb 25 '11 at 17:38

3 Answers3

20

I've looked into this library for you and found the following (warning - it's bad news!):

  1. There is no released version of ExcelLibrary that allows access to cell colours.

  2. In the unreleased source code there is a BackColor property in the new CellStyle class, however there is no property to represent foreground colour.

  3. The BackColor property is not persisted when the workbook is saved. It is only used to set the background colour of a cell when the workbook is loaded.

If use of colours is a requirement then use NPOI (as recommended by @jamietre). You can then set foreground and background colours like this:

HSSFCellStyle style1 = hssfworkbook.CreateCellStyle();

// cell background
style1.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.BLUE.index;
style1.FillPattern = HSSFCellStyle.SOLID_FOREGROUND;

// font color
HSSFFont font1 = hssfworkbook.CreateFont();
font1.Color = NPOI.HSSF.Util.HSSFColor.YELLOW.index;
style1.SetFont(font1);

cell.CellStyle = style1;
jing
  • 1,919
  • 2
  • 20
  • 39
Alex Angas
  • 59,219
  • 41
  • 137
  • 210
5

I know you may be tied to ExcelLibrary, but have you looked into EPPlus? http://epplus.codeplex.com/

It will do exactly what you're asking - easily (and more)

iivel
  • 2,576
  • 22
  • 19
  • EPPlus is NOT an alternative to ExcelLibrary. ExcelLibrary only handles XLS format. EPPlus only handles XLSX - and so is not a replacement. – Chris Rogers Apr 01 '15 at 01:37
  • Good call Chris - I hadn't considered that they may be stuck with the old binary Excel-Format for some reason. If that's the case, it would have to be some form of Interop library. NPOI would be the best choice (as noted by Alex) in that case. – iivel Apr 01 '15 at 13:37
1

I don't tested this but it seems that you the cell has a property called "Style" which defines the cellstyle. Here you can set the background color for a specific cell.

worksheet.Cells[0,0].Style.BackColor = Color.CornflowerBlue;
nhu
  • 470
  • 1
  • 5
  • 10
  • I've tested and unfortunately it doesn't work. :( Have a look at my answer for details. – Alex Angas Mar 02 '11 at 22:36
  • Hmm i just looked at the source on the googlecode repo. There you can find the prop for the style: [Excel Library Repo](http://code.google.com/p/excellibrary/source/browse/trunk/src/ExcelLibrary/Office/Excel/SpreadSheet/Cell.cs) on line 120. – nhu Mar 06 '11 at 16:21