使用C#获取一系列Excel单元格中的特定文本

我正在与Excel中的WPF应用程序工作。 在那个应用程序中,我有一个名称为Bulk。 该列包含两个选项,如YES和NO作为文本。 现在我需要指定字体为红色的YES选项和正常黑色的NO选项。 我得到了特定列的范围。 但我不知道我怎么得到YES选项和NO选项分开,也需要根据需要颜色的选项。

在这里我提到了我的代码:

foreach(Range Value in range.cells) { ??????? ??????? } 

任何人都可以告诉我这个的解决scheme。 我该如何进行这个过程。 提前致谢。

将这个类添加到您的项目中,并将命名空间更改为您的项目,并开始使用它来创build您想要的着色设置

就YES / NO检测而言,您可以执行以下操作:

  Microsoft.Office.Interop.Excel.Range range = myworksheet.UsedRange; //Start iterating from 1 not zero, 1 is the first row after notation of the current coloumn for (int i = 1; i <= range.Rows.Count; i++) { Microsoft.Office.Interop.Excel.Range myrange = myworksheet.get_Range(/*your column letter, ex: "A" or "B"*/ + i.ToString(), System.Reflection.Missing.Value); string temp = myrange.Text; if(temp.Contains("YES")) { //Do your YES logic } else if(temp.Contains("NO")) { //Do your No Logic } } 

尝试这个

 string strFileName = "D:\\test1.xlsx"; Microsoft.Office.Interop.Excel.Application ExcelObj = null; ExcelObj = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(strFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets; Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1); Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range("A11", "G21"); // Your requied range here foreach (Microsoft.Office.Interop.Excel.Range cell in range.Cells) { if(cell.TextToString()=="Yes") { } if(cell.TextToString()=="No") { } } 

更多信息请点击这里

http://msdn.microsoft.com/en-us/library/4zs9xy29(v=vs.80).aspx

至于单元格上的值检查,你可以使用Sherif Mahar Eaidbuild议的类,当我使用VBA来查找excel单元格时,我使用了更像这样的东西

“这是VB脚本,但。

if (Range("A1").Value = "DesiredString") Then Code End If

我几乎可以肯定的是,对于单元格对象,C#上有一个get方法,对于颜色,我认为是这样

YourRange.Font.Color = System.Drawing.Color.Black.ToArgb();

将工作…