Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing cell color of excel sheet via VB.NET

Tags:

excel

vb.net

I am writing some data from database to the excel via visual basic.net.I need to change background of some cells and also need to make text bold. I need something like that :

 xlWorkSheet.Cells(rownumber, 1).BackgroundColor = Color.Yellow
 xlWorkSheet.Cells(rownumber, 1).Font.isBold = True

Of course none of above is works.How can I achieve this? Thanks..

like image 781
dnur Avatar asked Aug 08 '11 13:08

dnur


3 Answers

You need to create a Excel.Style object, and apply that to a range. Like this:

Dim style As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle")
style.Font.Bold = True
style.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow)

xlWorkSheet.Cells(rownumber, 1).Style = "NewStyle"
like image 177
Edwin de Koning Avatar answered Oct 26 '22 05:10

Edwin de Koning


This worked perfect for me.

xlsWorkSheet.Cells(row, column).interior.color = Color.Green

like image 38
Jason Rule Avatar answered Oct 26 '22 05:10

Jason Rule


Thats few declaration that can help you for style an Excel
For color palette: http://dmcritchie.mvps.org/excel/colors.htm

Dim xlsCell As Excel.Range
xlsCell = xlWorkSheet.Range("A1")
xlsCell.Range("A5").Value = "TEXT"

With xlsCell.Range("A12:J12")
    .Merge()
    .Borders(XlBordersIndex.xlEdgeBottom).Weight = 2
    .Borders(XlBordersIndex.xlEdgeTop).Weight = 2
    .Borders(XlBordersIndex.xlEdgeLeft).Weight = 2
    .Borders(XlBordersIndex.xlEdgeRight).Weight = 2
    .Borders(XlBordersIndex.xlInsideHorizontal).Weight = 2
    .Borders(XlBordersIndex.xlInsideVertical).Weight = 2
    .Interior.ColorIndex = 15                        
    .WrapText = True
    .Font.Name = "Arial"
    .VerticalAlignment = Excel.XlHAlign.xlHAlignCenter
    .HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft
End With
like image 41
Emmanuel López Avatar answered Oct 26 '22 05:10

Emmanuel López