winform 读取Excel文件

使用 nuget 添加依赖库:Microsoft.Office.Interop.Excel

电脑要安装微软的Excel,由于是借助Excel的COM组件,所以打开文件要传绝对路径,以下是读取Excel的代码:

cs 复制代码
using System;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelExample
{
    internal class Example
    {
        public void ReadExcel(string path)
        {
            if (!File.Exists(path))
            {
                return;
            }
            var excel = new Excel.Application();
            excel.Visible = false;//设置为True的话,会显示Excel应用的窗口
            Excel.Workbook workbook = excel.Application.Workbooks.Open(path);
            Excel.Worksheet sheet = null;
            // 从1开始
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                sheet = workbook.Worksheets[i] as Excel.Worksheet;
                //Console.WriteLine("sheet name: " + sheet.Name);
                if (sheet.Name == "Sheet1")
                {
                    break;
                }
            }
            if (sheet == null) return;

            Excel.Range range = sheet.UsedRange;//有效范围(有数据的单元格)
            int rowCnt = range.Rows.Count;
            Excel.Range cell;
            //行号列号都是从1开始
            Console.WriteLine("行数: " + rowCnt);
            for (int row = 1; row <= rowCnt; row++)
            {
                Console.Write($"row {row} # ");
                cell = (Excel.Range)sheet.Cells[row, 8];//8是列号,第一列是1
                if (cell != null && cell.Value != null)
                {
                    string value = cell.Value.ToString();
                    Console.Write(value);
                }
                Console.WriteLine();
            }
            excel.Quit();
        }
    }
}
相关推荐
仓库日记14 小时前
Excel进销存何时该换?用3项检查判断是否需要软件
经验分享·excel·进销存·开单软件
用户03321266636715 小时前
如何使用 Python 将 JSON 转换为 Excel
python·excel
2601_967980111 天前
Python自动化办公:模块、库与样式调整教程
python·excel·自动化办公·openpyxl·样式调整
用户0332126663672 天前
使用 Python 轻松加密或解密 Excel 文档
python·excel
总裁余(余登武)3 天前
【python项目】:1操作EXCEl自动化开发
python·自动化·excel
ailitsoft5 天前
库存管理系统如何记录跨门店调拨后的收货差异?
excel·零售·软件需求
百事牛科技6 天前
Excel的三种密码:防看、防存、防乱改,各管各的
windows·excel
用户298698530147 天前
React 前端将 Excel 工作表导出为图片的技术实践
javascript·react.js·excel
用户0332126663678 天前
使用 Python 在 Excel 文档中添加水印
python·excel
科技新资讯9 天前
AI如何批量处理Excel文件? 从数据合并、清洗到自动生成报表,看看 AI Agent 怎么完成任务
大数据·人工智能·excel