Hi @Karson Mac ,
You can use Range.Interior property (Excel) to set the cell's background color.
.Cells.Interior.ColorIndex =3
Best Regards.
Jiachen Li
----------
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Export Datagridview to excel while maintaining cell color
Karson Mac
41
Reputation points
I was hoping someone could direct me or assist me with some code to complete a task I've been trying to resolve. I have a project that exports a datagridview to excel and it works perfectly. What I'm trying to do is maintain the cell formatting when I export. In my datagridview I have certain cells that turn red depending on certain conditions and I would like that to carry over when exporting to excel.
Any help would be appreciated...
Thanks,
Private Sub ToolStripButton3_Click(sender As Object, e As EventArgs) Handles ToolStripButton3.Click
Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim j As Integer
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
With ExcelSheet
For Each column As DataGridViewColumn In DataGridView1.Columns
.cells(1, column.Index + 1) = column.HeaderText
.Cells.Font.Size = 24
.Cells.Borders.LineStyle = Excel.XlLineStyle.xlContinuous
Next
For i = 1 To Me.DataGridView1.RowCount
.cells(i + 1, 1) = Me.DataGridView1.Rows(i - 1).Cells("id").Value
For j = 1 To DataGridView1.Columns.Count - 1
.cells(i + 1, j + 1) = DataGridView1.Rows(i - 1).Cells(j).Value
Next
Next
.Rows("1:1").Font.FontStyle = "Bold" 'Highlights header
End With
ExcelApp.WindowState = Excel.XlWindowState.xlMaximized
ExcelSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape
For col = 1 To 14
ExcelSheet.columns(col).AutoFit()
ExcelSheet.rows(col).AutoFit()
Next
ExcelApp.Visible = True
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
End Sub
Accepted answer
-
Jiachen Li-MSFT 33,121 Reputation points Microsoft Vendor
2023-01-12T06:09:36.2733333+00:00