简体   繁体   中英

How to set background color of DataRow in DataTable c#

I am exporting my DataTable to Excel. So before exporting, I added a new row, I want to set some background color to this row. Here is my code...

                    DataRow newRow = datatable3.NewRow();
                    for (int i = 0; i < datatable3.Columns.Count; i++)
                    {
                        newRow[i] = "Hello";
                    }

                //newRow.BackGroundColor = "Red" - Something like this.

Here I am exporting my DataTable to Excel.

                  using (XLWorkbook wb = new XLWorkbook())
                    {
                        foreach (DataTable dt in ds.Tables)
                        {
                            //Add DataTable as Worksheet.
                            wb.Worksheets.Add(dt, dt.TableName.ToString());
                        }
                        using (MemoryStream MyMemoryStream = new MemoryStream())
                        {
                            wb.SaveAs(MyMemoryStream);
                            return File(MyMemoryStream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ext);
                        }
                    }

It is showing like this .

在此处输入图片说明

How to change row background color?

it looks like you are using ClosedXMS dll. check their documentation on using colors

@Gopal

Just being a little specific to @Conor's answer!. You can try this-

//For a specific Datatable in a list of multiple

var ws = wb.Worksheets.Add(dt, dt.TableName.ToString());
for (int j = 1; j <= ds.Tables[3].Columns.Count; j++) //This is for fourth datatable/sheet
{
ws.Cell(2, j).Style.Fill.BackgroundColor = XLColor.FromArgb(255, 255, 0); //All columns of second row
}

XlColor.FromArgb(//RGB Color Code); This static method gives you the liberty of specifying the RGB color code which you can easily get through the excel template you are using.

You can use the Interior property found on an Excel.Range.

// The following just shows how the variables are created (based on creating a new Excel Spreadsheet)
var xlApp = new Excel.Application();
var xlWorkbook = xlApp.Workbooks.Add(Missing.Value);
var xlWorksheet = xlWorkbook.Worksheets[1];
// Now the actual code needed
var xlRange = xlWorksheet.UsedRange;
// This select the entire top row, but you can select your own range based on your data
var titleRange = xlRange.Range["A1", string.Concat(((char)(xlRange.Columns.Count + 64)), 1)];
// The following line sets the fill colour
titleRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue);

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