基于单元格值设置Excel工作表行颜色的格式



我有一个带有订单号列的网格,有了这些列,我检查了Excellents文件,如果excel文件中的特定单元格为空,则该行将为红色,否则为绿色。但我不明白为什么所有的东西都变成了红色。这是我的代码:

GridView View = gridView2 as GridView;
for (int i = 0; i <= gridView2.RowCount - 1; i++)
{
string status = (string)View.GetRowCellValue(i, View.Columns[0]);
if (File.Exists(@"I:OPTIMIZER" + status + @"_הזמנת_רכש_חומרים.xls"))
{
//Create an excel application object
Microsoft.Office.Interop.Excel.Application excelAppObj = new Microsoft.Office.Interop.Excel.Application();
excelAppObj.DisplayAlerts = false;
//Open the excel work book
Microsoft.Office.Interop.Excel.Workbook workBook = excelAppObj.Workbooks.Open(@"I:OPTIMIZER" + status + @"_הזמנת_רכש_חומרים.xls", 0, false, 5, "", "", false,
                Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
                true, false, 0, false, false);
//Get the first sheet of the selected work book
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets.get_Item(1);
var cellValue = (string)(worksheet.Cells[10, 5] as Microsoft.Office.Interop.Excel.Range).Value;
if (cellValue != null)
{
View.Appearance.Row.BackColor = Color.LightGreen;
View.Appearance.Row.ForeColor = Color.Black;
}
else
{
View.Appearance.Row.BackColor = Color.IndianRed;
View.Appearance.Row.ForeColor = Color.White;
}
workBook.Close(false);
excelAppObj.Quit();
}
}

我做错了什么?

您正在将颜色值应用于整个网格视图。

请使用此单元格所属的特定ROW,然后设置该特定ROW的颜色属性。您已经有了特定的ROW,其中的单元格值可能为null。使用"i"从网格中获取特定行并设置颜色。

给你。。。希望这能奏效。

GridViewRow gvCurrentRow = (GridViewRow)gridView2.Controls[0].Controls[i];
if (cellValue != null)
{
gvCurrentRow.BackColor = //set it to whatever you want
gvCurrentRow.ForeColor = //set it to whatever you want
}
else
{
gvCurrentRow.BackColor = //set it to whatever you want
gvCurrentRow.ForeColor = //set it to whatever you want
}

最新更新