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();
        }
    }
}
相关推荐
李昊哲小课10 分钟前
Python办公自动化教程 - 第2章 单元格样式魔法 - 让表格变得美观专业
开发语言·python·excel·openpyxl
孙同学20201 小时前
如何将 JSON 数据转换为 Excel 工作表
python·json·excel
奔跑的呱呱牛21 小时前
前端/Node.js操作Excel实战:使用@giszhc/xlsx(导入+导出全流程)
前端·node.js·excel·xlsx·sheetjs
Metaphor6921 天前
使用 Python 设置 Excel 表格的行高与列宽
开发语言·python·excel
SunnyDays10111 天前
如何使用 C# 创建、修改和删除 Excel 中的 VBA 宏(无需Microsoft Excel)
c#·excel·vba宏·创建vba宏·修改vba宏·删除vba宏
xinixini1 天前
2026年马年日历模板大全 可编辑Excel/Word/PSD/PDF素材合集
pdf·word·excel·日历
李昊哲小课2 天前
Python办公自动化教程 - 第7章 综合实战案例 - 企业销售管理系统
开发语言·python·数据分析·excel·数据可视化·openpyxl
葡萄城技术团队2 天前
Excel 科普:循环引用是“错误”还是“黑科技”?
excel
李昊哲小课2 天前
Python办公自动化教程 - openpyxl让Excel处理变得轻松
python·信息可视化·excel
李昊哲小课2 天前
Python办公自动化教程 - 第1章 openpyxl基础入门 - 第一次用代码操控Excel
开发语言·python·excel·openpyxl