检查 excel 第 3 列中的每个值,如果小于 4,则更改行颜色?C#.
本文关键字:小于 颜色 如果 检查 excel | 更新日期: 2024-10-25 15:16:46
我正在创建一个Excel工作表并使用c#填充值。
在保存之前,我想检查 excel 工作表的第 3 列并检查每个值是否小于 4。如果是,我想将该行更改为红色。
这是我到目前为止尝试过的:
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook worKbooK;
Microsoft.Office.Interop.Excel.Worksheet worKsheeT;
Microsoft.Office.Interop.Excel.Range celLrangE;
int totalcount = 0;
excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = false;
excel.DisplayAlerts = false;
worKbooK = excel.Workbooks.Add(Type.Missing);
worKsheeT = (Microsoft.Office.Interop.Excel.Worksheet)worKbooK.ActiveSheet; worKsheeT.Name = "Model Results";
worKsheeT.Cells[1, 1] = "Name";
worKsheeT.Cells[1, 2] = "Id";
worKsheeT.Cells[1, 3] = "Sales";
for (int totalcount= 3; totalcount< dataGridView2.Columns.Count; )
{
GetSalesNumbers();
worKsheeT.Cells[totalcount, 1] = Name;
worKsheeT.Cells[totalcount, 2] = Id;
worKsheeT.Cells[totalcount, 3] = SalesNumber;
totalcount ++;
}
celLrangE = worKsheeT.Range[worKsheeT.Cells[1, 1], worKsheeT.Cells[totalcount + 5, 15]];
celLrangE.EntireColumn.AutoFit();
Excel.Range usedRange = worKsheeT.UsedRange;
Excel.Range rows = usedRange.Rows;
int count = 0;
foreach (Excel.Range row in rows)
{
if (count > 0)
{
Excel.Range firstCell = row.Cells[count,3];
string firstCellValue = firstCell.Value as String;
if (Convert.ToDouble(firstCellValue)<4)
{
row.Interior.Color = System.Drawing.Color.Red;
}
}
count++;
}
但这不起作用,它一直将单元格值获取为 Null
这就是我最终使用的,我放弃了其他代码
celLrangE = worKsheeT.Range[worKsheeT.Cells[1, 1],worKsheeT.Cells[totalcount + 5, 15]];
celLrangE.EntireColumn.AutoFit();
for (int row = 3; row <= totalcount; row++)
{
if (Convert.ToDouble(worKsheeT.Cells[row, 3].Value) < 4)
{
Excel.Range rows = worKsheeT.Range[worKsheeT.Cells[row,1],worKsheeT.Cells[row,15]];
rows.Interior.Color = System.Drawing.Color.Red;
}
}