Highlighting data with different colors in Excel using C # in Windows applications

I am working with a windows application. I need to figure out how to highlight data with different colors and styles in Excel. I use C # to export data to excel.

This is the code that I use to export a DataTable to Excel,

private void btnExportexcel_Click(object sender, EventArgs e) { oxl = new Excel.Application(); oxl.Visible = true; oxl.DisplayAlerts = false; wbook = oxl.Workbooks.Add(Missing.Value); wsheet = (Excel.Worksheet)wbook.ActiveSheet; wsheet.Name = "Customers"; DataTable dt = clsobj.convert_datagrid_orderlist_to_datatable(dvgorderlist); int rowCount = 1; foreach (DataRow dr in dt.Rows) { rowCount += 1; for (int i = 1; i < dt.Columns.Count + 1; i++) { // Add the header the first time through if (rowCount == 2) { wsheet.Cells[1, i] = dt.Columns[i - 1].ColumnName; } wsheet.Cells[rowCount, i] = dr[i - 1].ToString(); } } range = wsheet.get_Range(wsheet.Cells[1, 1], wsheet.Cells[rowCount, dt.Columns.Count]); range.EntireColumn.AutoFit(); } wsheet = null; range = null; } 
+4
source share
1 answer

You need to get the β€œInterior” object of the cell or range and set the color on it.

 Range cellRange = (Range)wsheet.Cells[rowCount, i]; cellRange.Interior.Color = 255; 

Excel colors are a whole sequence, so you need to calculate the value of the color you want. You may find this method useful:

 public static int ConvertColour(Color colour) { int r = colour.R; int g = colour.G * 256; int b = colour.B * 65536; return r + g + b; } 

Then you can simply do this:

 cellRange.Interior.Color = ConvertColour(Color.Green); 

You can set the text style using the .font property:

 cellRange.Font.Size = "20"; cellRange.Font.Bold = true; 

There are other properties like Color , Italic and Underline that you can use to get the style you want.

+6
source

Source: https://habr.com/ru/post/1303657/


All Articles