You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#读取Excel的控制台程序如何新增关键词搜索功能

C# 控制台Excel关键词搜索功能实现

针对你的需求,在原有代码基础上新增关键词搜索逻辑,同时修复原有代码的单元格读取错误,修改后的完整代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;

namespace ReadFromExcelComponente
{
    class Program
    {
        static void Main(string[] args)
        {
            Excel.Application ExcelApp = null;
            Excel.Workbook workbook = null;
            try
            {
                // 初始化Excel对象
                ExcelApp = new Excel.Application();
                // 请替换为你实际的Excel文件完整路径
                workbook = ExcelApp.Workbooks.Open(@"D:\你的Excel文件路径.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets.get_Item(1);
                Excel.Range range = worksheet.UsedRange;
                int row = 0;
                int column = 0;

                // 新增:接收用户输入的搜索关键词
                Console.WriteLine("请输入要搜索的关键词:");
                string keyword = Console.ReadLine()?.Trim();
                if (string.IsNullOrEmpty(keyword))
                {
                    Console.WriteLine("错误:搜索关键词不能为空");
                    return;
                }
                int matchCount = 0;

                List<String> myList = new List<string>();
                for (row = 1; row <= range.Rows.Count; row++)
                {
                    for (column = 1; column <= range.Columns.Count; column++)
                    {
                        Excel.Range cell = range.Cells[row, column] as Excel.Range;
                        if (cell?.Value2 != null)
                        {
                            string cellValue = cell.Value2.ToString();
                            // 原有输出所有单元格内容的逻辑,不需要可以注释
                            Console.WriteLine($"列号: {column} --> {cellValue}");
                            myList.Add(cellValue);

                            // 新增:匹配判断,忽略大小写,需要大小写敏感可删除StringComparison参数
                            if (cellValue.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
                            {
                                matchCount++;
                                Console.WriteLine($"* 匹配到结果:行号 {row},列号 {column},内容:{cellValue}");
                            }
                        }
                    }
                }

                Console.WriteLine($"搜索完成,共找到 {matchCount} 处匹配结果");
                Console.WriteLine(myList[2]);
                Console.WriteLine(range.Cells[2, 2].Value);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"运行出错:{ex.Message}");
            }
            finally
            {
                // 确保资源释放,避免残留Excel后台进程
                workbook?.Close(true, null, null);
                ExcelApp?.Quit();
            }
            Console.ReadKey();
        }
    }
}

核心改动说明:

  • 新增用户输入接收与校验逻辑,避免空关键词搜索
  • 修复原有代码中单元格值读取的索引错误,避免触发空引用异常
  • 新增兼容低版本.NET框架的大小写不敏感匹配逻辑,可按需调整为大小写敏感匹配
  • 匹配到结果时同步输出单元格的行号、列号和具体内容,方便快速定位
  • 新增异常捕获和资源释放逻辑,避免Excel进程残留在后台

注意:请务必将代码中Workbooks.Open方法的第一个参数替换为你本地实际的Excel文件完整路径,否则会无法正常读取文件。

内容的提问来源于stack exchange,提问作者new programmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 14:06:03