Question : How to import Excel worksheet to DataGridView keeping cell colors

Hi there

I am developing a small app to help manage huge Excel worksheets.
These worksheets have multiple cells colored within.
I am loading the worksheets to a DataGridView as show below but I want to keep the cell colors.
Any ideias on how to achieve this? Would help if I didn't have to cycle all cells as the worksheets have near to on hundred columns and close to four hundred rows.

Regards
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
Dim connectionStringTemplate As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"""
 
                Dim connectionString As String = String.Format(connectionStringTemplate, sFileName)
                Dim sqlSelect As String = "SELECT * FROM [Sheet1$];"
                ' Load the Excel worksheet into a DataTable
                Dim workbook As DataSet = New DataSet()
                Dim excelAdapter As System.Data.Common.DataAdapter = New System.Data.OleDb.OleDbDataAdapter(sqlSelect, connectionString)
                Try
                    excelAdapter.Fill(workbook)
                    Dim worksheet As DataTable = workbook.Tables(0)
                    dgv.DataSource = worksheet
 
                Catch
'MANAGE EXCEPTION
 
                End Try

Answer : How to import Excel worksheet to DataGridView keeping cell colors

Here it is again, tidied up a bit, and using the first row as the HeaderText for the columns.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
        Dim xlApp As New Microsoft.Office.Interop.Excel.Application
        Dim xlWB As Microsoft.Office.Interop.Excel.Workbook = xlApp.Workbooks.Open("C:\Path\File.xls")
        Dim xlWS As Microsoft.Office.Interop.Excel.Worksheet = xlWB.Worksheets("Sheet1")
 
        DataGridView1.RowCount = xlWS.UsedRange.Rows.Count - 1
        DataGridView1.ColumnCount = xlWS.UsedRange.Columns.Count
 
        Try
            For c As Integer = 1 To xlWS.UsedRange.Columns.Count
                DataGridView1.Columns(c - 1).HeaderText = xlWS.UsedRange.Cells(1, c).Value
            Next
            For r As Integer = 2 To xlWS.UsedRange.Rows.Count
                For c As Integer = 1 To xlWS.UsedRange.Columns.Count
                    With DataGridView1(c - 1, r - 2)
                        .Value = xlWS.UsedRange.Cells(r, c).Value
                        .Style.BackColor = ColorTranslator.FromOle(xlWS.UsedRange.Cells(r, c).Interior.Color)
                    End With
                Next
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            xlWS = Nothing
            xlWB.Close(False)
            xlWB = Nothing
            xlApp.Quit()
            xlApp = Nothing
        End Try
Random Solutions  
 
programming4us programming4us