【问题标题】:Get Specific Text in a Range of Excel cells using C#使用 C# 获取 Excel 单元格区域中的特定文本
【发布时间】:2023-03-30 06:25:01
【问题描述】:

我正在使用 excel 处理 WPF 应用程序。在该应用程序中,我的列名为 Bulk。该列包含两个选项,例如 YES 和 NO 作为文本。现在我需要将 YES 选项的字体指示为红色,NO 选项指示为 Normal Black 颜色。 我得到了那个特定列的范围。但我不知道如何分别获得 YES 选项和 NO 选项,并且我需要根据需要为这些选项着色。

这里我提到了我的代码:

foreach(Range Value in range.cells)
{

???????
???????
}

任何人请告诉我这个解决方案。我该如何进行这个过程。提前致谢。

【问题讨论】:

标签: c# wpf excel


【解决方案1】:

试试这个

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

【讨论】:

    【解决方案2】:

    将此class 添加到您的项目并将命名空间更改为您的并开始使用它来创建您想要的着色设置

    就您的 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
                }
            }
    

    【讨论】:

    • 不应该在i &lt;= range.Rows.Count 时运行迭代吗?
    【解决方案3】:

    至于对单元格的值检查,您可以使用 Sherif Mahar Eaid 建议的类, 当我使用 VBA 查找 excel 单元格时,我使用的东西看起来更像这样

    ' 这是 VB 脚本。

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

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

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

    会起作用的...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      相关资源
      最近更新 更多