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();
        }
    }
}
相关推荐
跨境猫小妹6 小时前
跨境电商订单导出CSV用Excel打开后订单号变成科学计数法如何定位并修复
excel·跨境电商·营销策略
weixin_4404016917 小时前
大数据技术-数据分析(EXcel+Python数据处理+SQL)
大数据·python·数据分析·excel
jaysee-sjc1 天前
【苍穹外卖】Day12:工作台数据看板与 Excel 报表导出
java·开发语言·数据库·spring boot·spring·微信·excel
ms365copilot2 天前
Copilot 代理开始进入Word、Excel、PowerPoint,不再只是“问一句答一句”
word·excel·copilot
wuyk5552 天前
PyQt6-第14讲-数据库与Excel双向同步
数据库·python·ui·excel·pyqt
qq_364682152 天前
AI如何将录音内容自动整理成Excel清单
人工智能·excel
Logic1012 天前
Excel信息+照片文件夹,自动合成word格式化文档
word·excel·办公自动化·邮件合并·office技巧·自动插入图片·插入域
Data-Miner3 天前
一个省大模型积分的 Excel 数据处理方案:脱敏生成逻辑,脚本复用把 token 降到 0
人工智能·windows·excel
Logic1013 天前
表格智能记账3 销售与库存智能联动,自动标红库存预警
excel·条件格式·excel技巧·vlookup·sumif
技术小甜甜4 天前
【Copilot】能选 Claude 和 GPT-6 了,Excel 分析该交给谁
gpt·excel·copilot·claude·microsoft365·gpt-6