Free Support Forum - aspose.com

Could not apply background color on the cell

Hi, I have no idea why I could not apply background color on the cell. Please check my code

Dim cellstyle_red As Aspose.Cells.Style = A1cell.GetStyle
cellstyle_red.VerticalAlignment = TextAlignmentType.Top
cellstyle_red.HorizontalAlignment = TextAlignmentType.Center
cellstyle_red.Borders(BorderType.BottomBorder).LineStyle = CellBorderType.Thin
cellstyle_red.Borders(BorderType.LeftBorder).LineStyle = CellBorderType.Thin
cellstyle_red.Borders(BorderType.RightBorder).LineStyle = CellBorderType.Thin
cellstyle_red.Borders(BorderType.TopBorder).LineStyle = CellBorderType.Thin
cellstyle_red.BackgroundColor = System.Drawing.Color.Red
cellstyle_red.Pattern = BackgroundType.Solid
cellstyle_red.Number = 1

If (student_list(y, no_of_report + 7 - 4)) <> “” Then

                difference = Val(student_list(y, no_of_report + 7 - 2)) - Val(student_list(y, no_of_report + 7 - 4))

            Else

                difference = 0

            End If

            sheet.Cells(row, col).PutValue(difference.ToString, True, True) '1

            'Debug.Print(Val(TB_Diff.Text))

            If difference <= Val(TB_Diff.Text) Then

                sheet.Cells(row, col).SetStyle(cellstyle_red)
                'sheet.GetRow(row).GetCell(col).CellStyle = headerCellStyle8

            Else

                sheet.Cells(row, col).SetStyle(cellstyle_center)
                'sheet.GetRow(row).GetCell(col).CellStyle = headerCellStyle6

            End If

Please help

@churchilllee

Thanks for using Aspose APIs.

The background color is called Fill Color.
The foreground color is called Font Color.

You can set the fill color of the cell using the Style.ForegroundColor property.
You can set the font color of the cell using the Style.Font.Color property.

Please see the following sample code and its output Excel file for your reference.

Download Link:
output Excel file.zip (5.6 KB)

VB. NET

'Create workbook
Dim wb As New Workbook()

'Access first worksheet
Dim ws As Worksheet = wb.Worksheets(0)

'Access cell B4
Dim cell As Cell = ws.Cells("B4")

cell.PutValue("Sample B4")

'Set the fill color and font color of the cell
Dim st As Style = cell.GetStyle()
st.Pattern = BackgroundType.Solid

'This is fill color
st.ForegroundColor = Color.Yellow
'This is font color
st.Font.Color = Color.Red

'Set the cell style
cell.SetStyle(st)

'Save the workbook
wb.Save("output.xlsx")

C#

//Create workbook
Workbook wb = new Workbook();

//Access first worksheet
Worksheet ws = wb.Worksheets[0];

//Access cell B4
Cell cell = ws.Cells["B4"];

cell.PutValue("Sample B4");

//Set the fill color and font color of the cell
Style st = cell.GetStyle();
st.Pattern = BackgroundType.Solid;

//This is fill color
st.ForegroundColor = Color.Yellow;
//This is font color
st.Font.Color = Color.Red; 

//Set the cell style
cell.SetStyle(st);

//Save the workbook
wb.Save("output.xlsx");