C# 循环遍历列,当找到空单元格时,为整行着色?
我想循环遍历一列,当我找到一个空单元格,或者一个包含特定数字的单元格时,整个行都要上色 我试过的是这个(以及它的一些变体),但它不起作用:C# 循环遍历列,当找到空单元格时,为整行着色?,c#,excel,office-interop,excel-interop,C#,Excel,Office Interop,Excel Interop,我想循环遍历一列,当我找到一个空单元格,或者一个包含特定数字的单元格时,整个行都要上色 我试过的是这个(以及它的一些变体),但它不起作用: xl.Range end = MySheet.Cells.SpecialCells(xl.XlCellType.xlCellTypeLastCell, Type.Missing); xl.Range start = MySheet.get_Range("Q2", end ); if (start.Value == null) { start.Ent
xl.Range end = MySheet.Cells.SpecialCells(xl.XlCellType.xlCellTypeLastCell, Type.Missing);
xl.Range start = MySheet.get_Range("Q2", end );
if (start.Value == null)
{
start.EntireRow.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
}
任何形式的帮助或好主意都将不胜感激。更新: 找到了解决此问题的方法:
xl.Range first_range = MySheet.Cells.SpecialCells(xl.XlCellType.xlCellTypeLastCell, Type.Missing);
xl.Range usedRange = MySheet.get_Range("Q2", first_range);
xl.Range rows = usedRange.Rows;
int count = 0;
foreach (xl.Range row in rows)
{
if (count > 0)
{
xl.Range firstcell = row.Cells[1];
string firstCellValue = firstcell.Value as string;
if (string.IsNullOrEmpty(firstCellValue))
{
row.EntireRow.Interior.Color = System.Drawing.Color.Red;
}
}
count++;
}
当使用for&foreach循环处理大数据(如10000行)时,我得到 “OutOfMemory”异常 所以最好的解决方案是使用Lambda表达式
//best practice access cell by number not by string
yourWorksheet.RangeUsed().Rows(r => string.IsNullOrWhiteSpace(r.Cell(1).Value.ToString()))
.ForEach(r => r.Style.Fill.SetBackgroundColor(XLColor.Red));
这是Excel VBA吗?如果你想在单元格中循环,那么你需要一个循环,即:对于每个、For或while语句。@D.O.不,它是C#Interop-Excel,那么你的问题必须在“C#questions”中,而不是在“Excel questions”@D.O中。它在C#和Excel下,也在office Interop和Excel Interop下