检查excel第3列中的每个值,如果小于4,请更改行颜色? C#

时间:2016-04-20 15:27:10

标签: c# excel

我正在创建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

1 个答案:

答案 0 :(得分:0)

这是我最终使用的,我放弃了其他代码

            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;
                }


            }