vb.net中如何获取到excel单元格的颜色
目前查了很多文章,给单元格设置颜色的很多,但获取颜色值的没查到
下面是我写的代码
但发现获取到的值都是 16777215
不知道该如何正确获取
Function ReadExcel(ByVal FileName As String)
Dim txt As String
Dim style1 As Excel.Style
Dim style2 As Excel.Style
AppXls = New Microsoft.Office.Interop.Excel.Application
AppXls.Workbooks.Open(FileName)
AppXls.Visible = False
AppWokBook = AppXls.Workbooks(1)
AppSheet = AppWokBook.Sheets(1)
style1 = AppSheet.Cells(2, 1).style
style2 = AppSheet.Cells(2, 2).style
Label2.Text = style1.Interior.Color
Label3.Text = style2.Interior.Color
mydataset = txt
AppXls.Quit()
AppWokBook = Nothing
AppSheet = Nothing
AppXls = Nothing
Return mydataset
End Function
获取Range.Interior.Color,不是Ceil.Style.Interior.Color
示例代码来源:https://www.w3dev.cn/article/20230121/CSharp-Vb.net-Get-Excel-Cell-BackgroudColor-Demo.aspx
Imports System.Linq
Imports System.Collections.Generic
Imports Microsoft.VisualBasic
Imports System.Data.OleDb
Module Module1
Function RGB(color)
r = &HFF And color
g = &HFF00 And color
g >>= 8
b = &HFF0000 And color
b >>= 16
Return $"RGB({r}, {g}, {b})"
End Function
Sub Main()
AppXls = New Microsoft.Office.Interop.Excel.Application
AppXls.Workbooks.Open("E:\Demos\CSharp\ConsoleApp\Demo\d.xlsx")
AppXls.Visible = False
AppWokBook = AppXls.Workbooks(1)
AppSheet = AppWokBook.Sheets(1)
range = AppSheet.Range(AppSheet.Cells(1, 1), AppSheet.Cells(1, 1))
color = range.Interior.Color.ToString()
Console.WriteLine($"{color}==>{RGB(Integer.Parse(color))}") '红
range = AppSheet.Range(AppSheet.Cells(2, 1), AppSheet.Cells(2, 1))
color = range.Interior.Color.ToString()
Console.WriteLine($"{color}==>{RGB(Integer.Parse(color))}") '绿
range = AppSheet.Range(AppSheet.Cells(3, 1), AppSheet.Cells(3, 1))
color = range.Interior.Color.ToString()
Console.WriteLine($"{color}==>{RGB(Integer.Parse(color))}") '蓝
AppXls.Quit()
Console.ReadKey()
End Sub
End Module
该回答引用GPTᴼᴾᴱᴺᴬᴵ
您可以使用以下代码获取Excel单元格的颜色值:
Dim style1 As Excel.Style
Dim style2 As Excel.Style
Dim color1 As Integer
Dim color2 As Integer
' 打开Excel文件
AppXls = New Microsoft.Office.Interop.Excel.Application
AppXls.Workbooks.Open(FileName)
AppXls.Visible = False
AppWokBook = AppXls.Workbooks(1)
AppSheet = AppWokBook.Sheets(1)
' 获取单元格样式和颜色
style1 = AppSheet.Cells(2, 1).Style
style2 = AppSheet.Cells(2, 2).Style
color1 = style1.Interior.Color
color2 = style2.Interior.Color
' 将颜色值转换成RGB值
Dim r1 As Integer = color1 Mod 256
Dim g1 As Integer = color1 \ 256 Mod 256
Dim b1 As Integer = color1 \ 256 \ 256 Mod 256
Dim r2 As Integer = color2 Mod 256
Dim g2 As Integer = color2 \ 256 Mod 256
Dim b2 As Integer = color2 \ 256 \ 256 Mod 256
' 显示颜色值
Label2.Text = "RGB(" & r1 & ", " & g1 & ", " & b1 & ")"
Label3.Text = "RGB(" & r2 & ", " & g2 & ", " & b2 & ")"
' 关闭Excel文件
AppXls.Quit()
AppWokBook = Nothing
AppSheet = Nothing
AppXls = Nothing
其中,使用style1.Interior.Color和style2.Interior.Color可以获取单元格的颜色值,但是这个值是Excel的颜色索引值,需要将其转换为RGB值才能得到具体的颜色。