0
votes

I need to know how it's possible to export the rows from my DataGridView to Excel, including their row color.

At this moment I export them but the colors are blank/white/default color.

I need to do this in vb.net

2
How do you export them? If you can, post your code so that we can suggest the easiest change. There are too many possible answers to this question without more details.Slai
Do you use excel-interop, xml format or any other possible solution to export to excel?Reza Aghaei

2 Answers

1
votes

You could try this one:

  For Each drow As DataGridViewRow In datagrid1.Rows
      xcel.Cells(yourRowInt, yourColInt).Interior.Color = drow.DefaultCellStyle.BackColor
  Next
0
votes

Can you try it like this?

    Private Sub button5_Click(ByVal sender As Object, ByVal e As EventArgs)
        Const WORKSHEETSTARTROW As Integer = 1
        Const WORKSHEETSTARTCOL As Integer = 1
        Dim excelApp = New Excel.Application
        excelApp.Visible = true
        Dim excelbk As Excel.Workbook = excelApp.Workbooks.Add(Type.Missing)
        Dim xlWorkSheet1 As Excel.Worksheet = CType(excelbk.Worksheets("Sheet1"),Excel.Worksheet)
        Dim worksheetRow As Integer = WORKSHEETSTARTROW
        Dim rowCount As Integer = 0
        Do While (rowCount  _
                    < (dataGridView1.Rows.Count - 1))
            Dim worksheetcol As Integer = WORKSHEETSTARTCOL
            Dim colCount As Integer = 0
            Do While (colCount  _
                        < (dataGridView1.Columns.Count - 1))
                Dim xlRange As Excel.Range = CType(xlWorkSheet1.Cells(WORKSHEETSTARTROW, worksheetcol),Excel.Range)
                xlRange.Value2 = dataGridView1.Columns(colCount).Name
                worksheetcol = (worksheetcol + 1)
                If (Not (dataGridView1.Rows(rowCount).Cells(colCount).Style.Font) Is Nothing) Then
                    xlRange.Font.Bold = dataGridView1.Rows(rowCount).Cells(colCount).Style.Font.Bold
                    xlRange.Font.Italic = dataGridView1.Rows(rowCount).Cells(colCount).Style.Font.Italic
                    xlRange.Font.Underline = dataGridView1.Rows(rowCount).Cells(colCount).Style.Font.Underline
                    xlRange.Font.FontStyle = dataGridView1.Rows(rowCount).Cells(colCount).Style.Font.FontFamily
                End If

                worksheetcol = (worksheetcol + 1)
                colCount = (colCount + 1)
            Loop

            worksheetRow = (worksheetRow + 1)
            rowCount = (rowCount + 1)
        Loop

    End Sub