Solved

How to import Excel worksheet to DataGridView keeping cell colors

Posted on 2008-10-16
6
1,411 Views
Last Modified: 2008-10-16
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
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

Open in new window

0
Comment
Question by:vercesi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
6 Comments
 
LVL 47

Expert Comment

by:Wayne Taylor (webtubbs)
ID: 22729867
vercesi,

It's impossible to determine the cell color through ADO.Net, so unfortunately the only way to color the DatGridView cells is to iterate through each cell in the imported range. Something like the below code snippet. Yes, it could take a while, but that is the only option you have for importing the cell colors.

Wayne
        Dim xlApp As Object = CreateObject("Excel.Application")
        Dim xlWB As Object = xlApp.Workbooks.Open("C:\Path\File.xls")
        Dim xlWS As Object = xlWB.Worksheets("Sheet1")
 
        DataGridView1.RowCount = xlWS.UsedRange.Rows.Count
        DataGridView1.ColumnCount = xlWS.UsedRange.Columns.Count
 
        Try
            For r As Integer = 1 To xlWS.UsedRange.Rows.Count
                For c As Integer = 1 To xlWS.UsedRange.Columns.Count
                    With DataGridView1(c - 1, r - 1)
                        .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
            'empty catch
        End Try
 
        xlWS = Nothing
        xlWB.Close(False)
        xlWB = Nothing
        xlApp.Quit()
        xlApp = Nothing

Open in new window

0
 
LVL 1

Author Comment

by:vercesi
ID: 22729908
Just tried your solution but got an error:

"Old format or invalid type format"

Do I need to add some expecific reference?
0
 
LVL 47

Expert Comment

by:Wayne Taylor (webtubbs)
ID: 22730059
Hmm. I just noticed in your code you are using XL2007. If you add a reference to "Microsoft Excel 12.0 Object Library", the below should work.

If not, it'd help to know which line caused the error.
        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
        DataGridView1.ColumnCount = xlWS.UsedRange.Columns.Count
 
        Try
            For r As Integer = 1 To xlWS.UsedRange.Rows.Count
                For c As Integer = 1 To xlWS.UsedRange.Columns.Count
                    With DataGridView1(c - 1, r - 1)
                        .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
            'empty catch
        End Try
 
        xlWS = Nothing
        xlWB.Close(False)
        xlWB = Nothing
        xlApp.Quit()
        xlApp = Nothing

Open in new window

0
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
LVL 47

Accepted Solution

by:
Wayne Taylor (webtubbs) earned 125 total points
ID: 22730105
Here it is again, tidied up a bit, and using the first row as the HeaderText for the columns.
        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

Open in new window

0
 
LVL 1

Author Comment

by:vercesi
ID: 22730420
Still got the same error.

I have googled the error and found this:
"In some deployment scenarios, you must know the locale identifier (LCID) for a language in order to install the correct MUI Pack."

I will try the solution provided (installing MUI Pack) and get back on this.
0
 
LVL 1

Author Comment

by:vercesi
ID: 22731029
I've got it working using:

System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US")

Thanks you
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question