如何使用封闭的xml比较列值?

问题描述 投票:0回答:1

我在Excel中有一个表格

 col1 col2
 2      4
 1      5   
 5      3
 8      7

我需要比较2列,col1 & col2。如果col2>col1列的值,那么在col2列的单元格中填入红色。如果col2列的值

我写了一个例子方法,但我不知道如何进一步修正。

private static void BackroundColor(string filePathNameExcel) 
{
    int i = 1;
    using (XLWorkbook wb = new XLWorkbook(filePathNameExcel))
    {
        IXLWorksheet ws = wb.Worksheet("sheetMy");
        int col = 1;
        for (int j = 1; j <= col; j++)
        {
            if (j == 3)
            {
                for (int irow = 1; irow <= i; irow++)
                {
                    if (ws.Cell(irow, 3).GetString() == "2")  
                    {
                        string dat = ws.Cell(irow, 3).GetString();
                        ws.Cell(irow, 1).Style.Fill.BackgroundColor = XLColor.Red;
                    }
                }
            }
        }
        wb.SaveAs(filePathNameExcel, true);
    }
}
c# excel closedxml
1个回答
0
投票

如果没有看到更多的数据格式,我无法完全理解你的代码逻辑,所以我做了一些假设,并在这个例子中简化了它。

开始数据

enter image description here

编码

private static void BackroundColor(string filePathNameExcel)
{
    using (XLWorkbook wb = new XLWorkbook(filePathNameExcel))
    {
        IXLWorksheet ws = wb.Worksheet("sheetMy");
        int lastRow =  ws.LastRowUsed().RowNumber();

        // Loop each row
        for (int irow = 1; irow <= lastRow; irow++)
        {
            // Check if column 1 row value is less then column 2 row value
            if ((double)ws.Cell(irow, 1).Value <  (double)ws.Cell(irow,2).Value)
            {
                ws.Cell(irow, 2).Style.Fill.BackgroundColor = XLColor.Red;
            }
        }

        wb.SaveAs(filePathNameExcel, true);
    }
}

结果

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.