VB.Net datagrid导入带有颜色的excel单元格

时间:2017-02-17 19:24:38

标签: vb.net datagridview

我有一个数据网格视图,我在这个数据网格中导入Excel值,但是我看不到背面的单元格颜色。这是我的代码和图片。

如何将颜色从Excel传递到数据网格?

[enter image description here

Dim cmb As New DataGridViewComboBoxColumn()
    cmb.HeaderText = "Colum1"
    cmb.Name = "cmb"
    cmb.Items.Add("Select for Main Plot")
    cmb.Items.Add("Select")
    DataGridView1.Columns.Add(cmb)

    Dim conn As OleDbConnection
    Dim dta As OleDbDataAdapter
    Dim dts As DataSet
    Dim excel As String
    Dim OpenFileDialog As New OpenFileDialog

    OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
    OpenFileDialog.Filter = "All Files (*.*)|*.*|Excel files (*.xlsx)|*.xlsx|CSV Files (*.csv)|*.csv|XLS Files (*.xls)|*xls"

    If (OpenFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
    End If

    Dim fi As New FileInfo(OpenFileDialog.FileName)
    Dim FileName As String = OpenFileDialog.FileName

    excel = fi.FullName
    conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel + ";Extended Properties=Excel 12.0;")
    dta = New OleDbDataAdapter("Select * From [Sayfa1$]", conn)
    dts = New DataSet
    dta.Fill(dts, "[Sayfa1$]")
    DataGridView1.DataSource = dts
    DataGridView1.DataMember = "[Sayfa1$]"
    conn.Close()

1 个答案:

答案 0 :(得分:0)

史蒂夫指出......这是你必须实施的。由于您没有真正指定着色方案的工作原理,我将假设根据单元格中的值将决定单元格应具有的颜色背景。这是相当直接的,可以通过多种方式实现。

一种选择是创建一种方法,简单地遍历DataGridView中的所有单元格,并根据单元格的值相应地设置其颜色。但是,每次更改单元格值时,都必须重新运行该方法。

另一个选择是将此逻辑放在CellFormatting事件中。这样,在使用数据初始化DataGridView时将应用颜色,并且如果用户更改单元格值,也会更改颜色。

由于您发布的代码不会显示任何内容,因此您可能需要根据需要调整以下代码。

Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
  Dim cellValue As String
  Dim row As DataGridViewRow
  row = DataGridView1.Rows(e.RowIndex)
  If (Not row.IsNewRow) Then
    cellValue = row.Cells(e.ColumnIndex).Value
    If (cellValue IsNot Nothing) Then
      row.Cells(e.ColumnIndex).Style.BackColor = GetColor(cellValue)
    End If ' ignore empty cells
  End If ' ignore new row
End Sub

Private Function GetColor(colorValue As String) As Color
  Select Case colorValue
    Case "1"
      GetColor = Color.FromArgb(245, 129, 109)
    Case "2"
      GetColor = Color.FromArgb(251, 129, 113)
    Case "3"
      GetColor = Color.FromArgb(252, 155, 119)
    Case "4"
      GetColor = Color.FromArgb(250, 186, 119)
    Case "5"
      GetColor = Color.FromArgb(253, 208, 130)
    Case "6"
      GetColor = Color.FromArgb(253, 236, 129)
    Case "7"
      GetColor = Color.FromArgb(215, 224, 130)
    Case "8"
      GetColor = Color.FromArgb(178, 213, 130)
    Case "9"
      GetColor = Color.FromArgb(139, 201, 128)
    Case "10"
      GetColor = Color.FromArgb(100, 189, 122)
    Case Else
      GetColor = Color.White
  End Select
End Function