简体   繁体   中英

Format certain rows where a cell value meets a condition when exporting from VB.NET (DataGridView) to Excel

I am new to VB syntax, and im struggling with adding conditions to an excel export. I have a dataset (ds2) that populates a DataGridView (dgvBreaks).The data in the dataset will look something like this:

Emp_Name ClockDate Time_In Time_Out Total_Hours Actual_Hours Breaks Notes
Moloto, Joseph 04/04/2022 00:00 07:36:00 06:42:00 5,8 4,60 2 Clocked out on: 2022-04-05 -
Moloto, Joseph 04/05/2022 00:00 07:22:00 07:22:00 9,2 9,00 1
Moloto, Joseph 04/06/2022 00:00 07:40:00 16:31:00 8,9 8,80 0
Moloto, Joseph 04/07/2022 00:00 07:25:00 16:29:00 9,1 9,00 0
Moloto, Joseph 04/08/2022 00:00 07:34:00 15:35:00 8,0 8,90 0
Moloto, Joseph 04/11/2022 00:00 07:42:00 16:33:00 8,9 8,80 0

I want to export the data from the gridview or dataset to excel and format certain rows based on a cell value. FOR EXAMPLE: Highlight a row in red if the Actual hours is less than 8. so that this row would be in red:

Emp_Name ClockDate Time_In Time_Out Total_Hours Actual_Hours Breaks Notes
Moloto, Joseph 04/04/2022 00:00 07:36:00 06:42:00 5,8 4,60 2 Clocked out on: 2022-04-05 -

Currently I export the data to an excel sheet using the code below:

    Dim xlApp As Microsoft.Office.Interop.Excel.Application
    Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
    Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
    Dim misValue As Object = System.Reflection.Missing.Value
    Dim i As Integer
    Dim j As Integer
    xlApp = New Microsoft.Office.Interop.Excel.Application
    xlWorkBook = xlApp.Workbooks.Add(misValue)
    xlWorkSheet = xlWorkBook.Sheets("sheet1")
    For i = 0 To dgvDataBreaks.RowCount - 2
        For j = 0 To dgvDataBreaks.ColumnCount - 1
            For k As Integer = 1 To dgvDataBreaks.Columns.Count
                xlWorkSheet.Cells(1, k) = dgvDataBreaks.Columns(k - 1).HeaderText
                xlWorkSheet.Cells(i + 2, j + 1) = dgvDataBreaks(j, i).Value.ToString()
            Next
        Next
    Next
    Dim path As SaveFileDialog = New SaveFileDialog
    path.ShowDialog()
    If DialogResult.OK Then
        xlWorkSheet.SaveAs(path.FileName)
    End If
    xlWorkBook.Close()
    xlApp.Quit()
    releaseObject(xlApp)
    releaseObject(xlWorkBook)
    releaseObject(xlWorkSheet)
    MsgBox("You can find the file at: " + path.FileName)

But I am not sure how to add the conditional check. (How would I check only the 'Actual Hours' for instace?)

As JohnG stated in the comments, it is quite simple:

xlWorkSheet.Range(xlWorkSheet.Cells(i + 2, 1), xlWorkSheet.Cells(i + 2, 8)).Interior.Color = ColorTranslator.ToOle(Color.Red)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM