使用互操作C#迭代Excel工作表

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

我有一个DataTable,用于使用Interop创建工作表。一旦有了工作表,我想遍历该工作表以获取一些满足条件的单元格并在其中输入新值。

例如,下一张表是我的工作表,创建后,我要遍历工作表并尝试仅获取红色单元格中的值 ...因此,单元格必须满足条件。

enter image description here

如何使用SQLInterop获得这些值,有一些方法可以做到这一点?

c# excel visual-studio interop
1个回答
0
投票

您可以使用下面的代码来获取红色单元格中的值。

using Excel = Microsoft.Office.Interop.Excel;

 static void Main(string[] args)
        {
            string pathToExcelFile = @"D:\test.xlsx";

            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(pathToExcelFile, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

            Excel._Worksheet sheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
            Excel.Range ran = sheet.UsedRange;
            for (int x = 1; x <= ran.Rows.Count; x++)
            {
                for (int y = 1; y <= ran.Columns.Count; y++)
                {
                    var CellColor = sheet.UsedRange.Cells[x, y].Interior.Color; 
                    if(CellColor==GetCustomColor(Color.Red))
                    {
                        string value = sheet.Cells[x, y].value.ToString();
                        Console.WriteLine(value);
                    }
                }
            }
            Console.ReadKey();
        }
        private static  Double GetCustomColor(Color color)
        {
            int nColor = color.ToArgb();
            int blue = nColor & 255;
            int green = nColor >> 8 & 255;
            int red = nColor >> 16 & 255;
            return Convert.ToDouble(blue << 16 | green << 8 | red);
        }

Excel文件:

enter image description here

结果:

enter image description here

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