读取Excel单元格并设置行颜色
我正在使用Com Interop和C#。 我必须遍历一个Excel文件,在每个行中查找特定的值(总是在第2列)。 对于某些值,我需要将该行的背景颜色设置为红色。
我有麻烦:
- 读取单元格[i] [2]中第i行的值
- 设置该行的背景颜色。
基本上我正在寻找这样的东西(这是我可以find最好的谷歌search之后):
// ws is the worksheet for (int i = 1; i <= ws.Rows.Count; i++) { Range range = ws.Cells[i][2]; int count = Convert.ToInt32(range.Value2.ToString()); if (count >= 3) { Range chronic = ws.UsedRange.Rows[i]; chronic.EntireRow.Cells.Interior.Color = 0xFF0000; } }
当然这不起作用。 我无法摆脱阅读牢房的第一个障碍。 任何意见表示赞赏。
尝试这个。 该代码假定列2单元格中的值是一个数字。
using Excel = Microsoft.Office.Interop.Excel; using System.Reflection; Missing noValue = Missing.Value; Excel.Range conditionalCell; foreach (Excel.Range usedRange in ws.UsedRange.Rows) { conditionalCell = usedRange.Cells[noValue, 2] as Excel.Range; if (Convert.ToInt32(conditionalCell.Value2) >= 3) { usedRange.Cells.Interior.Color = Excel.XlRgbColor.rgbRed; } }