Search code examples
vb.netepplus

Comparing EPPlus Style Fill background Color with System.Drawing.Color gives error


I am using EPPlus library to read and modify contents on an excel file. The background colour on rows gets assigned initially when the excel file is processed first. New records will be added manually. Then when new records are added to this existing file, they won't have a background colour set. I wish to skip the already processed rows based on the background colour. But I get this error when trying to do a colour comparison.

Error 5 Value of type 'OfficeOpenXml.Style.ExcelColor' cannot be converted to 'System.Drawing.Color'.

 If Not myrow.Style.Fill.BackgroundColor = Color.LightSlateGray AndAlso myrow.Style.Font.Bold = True Then
            HasExcelRowBeenAlreadyProcessed = False
        Else
            HasExcelRowBeenAlreadyProcessed = True
        End If

I also tried this but somehow it is not working. Please, can someone assist?

 Dim oCellRGBVal = System.Drawing.ColorTranslator.FromHtml(myrow.Style.Fill.BackgroundColor.LookupColor.ToString).ToArgb

            HasExcelRowBeenAlreadyProcessed = False

            If Not oCellRGBVal = Color.LightSlateGray.ToArgb AndAlso myrow.Style.Font.Bold = True Then
                HasExcelRowBeenAlreadyProcessed = False
            Else
                HasExcelRowBeenAlreadyProcessed = True
            End If

Solution

  • Instead of trying to convert the background color, I would instead convert the initial color to a string.

        Dim colorAsString As String = Color.LightSlateGray.ToArgb.ToString("X2")
    
        If Not myrow.Style.Fill.BackgroundColor.Rgb = colorAsString AndAlso myrow.Style.Font.Bold = True Then
            HasExcelRowBeenAlreadyProcessed = False
        Else
            HasExcelRowBeenAlreadyProcessed = True
        End If
    

    This should work. Also, this let you store colorAsString so you don't need to calculate it everytime.