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();
        }
    }
}
相关推荐
一晌小贪欢1 天前
python-第15天:Python 列表推导式
开发语言·python·excel·数据可视化·python办公
tryxr2 天前
Chat2Excel 项目通用服务开发
java·开发语言·excel·java项目开发
Jazz_z2 天前
使用 Python 合并与取消合并 Excel 单元格
开发语言·python·excel
2601_962381863 天前
Python办公联动:Excel数据一键自动生成PPT图表
python·数据分析·自动化·excel·ppt
tryCbest4 天前
Excel常用公式(WPS vs Office)
excel·wps
taller_20005 天前
【006】何时用 Python?何时用 Excel 公式?一文讲清
python·excel·公式·pie·py
2601_949950635 天前
Word、PDF、Excel题目怎么快速整理?
pdf·word·excel
Eiceblue5 天前
React 项目实战:用 JavaScript 合并多个本地 Excel 文件
前端·javascript·react.js·excel
ms365copilot6 天前
Excel做完≠结束,Copilot一键生成汇报PPT
powerpoint·excel·copilot
城数派6 天前
1901-2025年中国省市县三级逐年平均气温数据集(Shp/Excel 格式)
excel