簡體   English   中英

如何在DataTable C#中設置DataRow的背景色

[英]How to set background color of DataRow in DataTable c#

我正在將DataTable導出到Excel。 因此,在導出之前,我添加了新行,我想為此行設置一些背景色。 這是我的代碼...

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

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

在這里,我將DataTable導出到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);
                        }
                    }

像這樣顯示。

在此處輸入圖片說明

如何更改行背景色?

看來您正在使用ClosedXMS dll。 查看他們有關使用顏色的文檔

@Gopal

只是針對@Conor的答案而已! 您可以嘗試-

//對於特定的數據表,在多個列表中

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顏色代碼); 此靜態方法使您可以自由指定RGB顏色代碼,您可以通過所使用的excel模板輕松獲得該顏色代碼。

您可以使用在Excel.Range上找到的Interior屬性。

// 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM