首页 > 解决方案 > 我想在我的 excel 工作表中找到重复的值并在 c# 中更改文本颜色

问题描述

我想在我的 excel 工作表中找到重复的值,并使用以下代码更改 c# 中的文本颜色:

            Excel.Application xlApp =
            new Excel.Application();
            //xlApp.Visible = true;
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(DtaSource1);
            Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;
        
            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;

            for(int k=1;k<=rowCount;k++)
            {
                for (int i = 1; i <= rowCount; i++)
                {

                    for (int j = 1; j <= colCount; j++)
                    {

                        if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j] == xlRange.Cells[k, 1])
                        {
                            xlRange.Cells[i, j].value = "00000";
                            xlWorksheet.SaveAs(DtaSource1);
                        }

                    }
                }
            }

但它不起作用,当我想保存更改时,它会抛出错误 excel 表只读!

标签: c#excel

解决方案


这是一个使用 Spire.XLS在 Excel 中突出显示重复值和唯一值的示例,也许您可​​以尝试一下。

//Load the Excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];

//Use conditional formatting to highlight duplicate values in range "A2:A10" with IndianRed color
ConditionalFormatWrapper format1 = sheet.Range["A2:A10"].ConditionalFormats.AddCondition();
format1.FormatType = ConditionalFormatType.DuplicateValues;
format1.BackColor = Color.IndianRed;

//Save the file            
workbook.SaveToFile("HighlightDuplicates.xlsx", ExcelVersion.Version2013);

推荐阅读