C# 读取 Excel xlsx 文件,显示在 DataGridView 中

编写 read_excel.cs 如下

cs 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.OleDb;

namespace ReadExcel
{
  public partial class Program
  {
    
    static void Main(string[] args)
    {
        if (args.Length <1){
            Console.WriteLine(" usage: read_excel your_file.xlsx ");
            return ;
        }
        if (! File.Exists(args[0])){
            Console.WriteLine("Error: {0} not exists.", args[0]);
            return ;
        }
        if (Path.GetExtension(args[0]) != ".xlsx"){
            Console.WriteLine("Tip: can only read file.xlsx");
        }
        string filePath = args[0]; // your_excel_file_path
 
        string connStr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"", filePath);
 
        using (OleDbConnection conn = new OleDbConnection(connStr))
        {
            conn.Open();
 
            string sheet1 = "Sheet1";
 
            string query = string.Format("SELECT * FROM [{0}$]", sheet1);
 
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
            {
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);
                int rows, cols;
                // 处理获取到的数据
                foreach (DataRow row in dataTable.Rows)
                {
                    rows = row.Table.Rows.IndexOf(row) +1;
                    foreach (DataColumn column in dataTable.Columns)
                    {
                        string value = row[column].ToString() ?? string.Empty;                       
                        cols = column.Ordinal +1;
                        Console.WriteLine("Cell({0:d},{1:d}): {2}", rows,cols,value);
                    }
                }
            }
        } 
        Console.ReadKey();
    }
  }
}

SET PATH=C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319;%PATH%

编译:csc.exe /t:exe read_excel.cs

环境:win10 64位系统 运行 \your\path\read_excel.exe test1.xlsx

错误信息:未在本地计算机上注册"Microsoft.ACE.OLEDB.12.0"提供程序。

搜索 Microsoft Access Database Engine 2016

我先下载了 accessdatabaseengine.exe 安装好后,还是运行出错。

卸载了32位版本,又下载了 AccessDatabaseEngine_X64.exe 安装好后,能运行了。

参考:C#读取Excel表格数据到DataGridView中和导出DataGridView中的数据到Excel

C#读取Excel表格数据到DataGridView中,代码如下

cs 复制代码
    private void btnShow_Click(object sender, EventArgs e)
    {   //首先根据打开文件对话框,选择excel表格
        OpenFileDialog fd = new OpenFileDialog();
        fd.Filter = "xlsx表格|*.xlsx"; //打开文件对话框筛选器
        string strPath;//文件完整的路径名
        if (fd.ShowDialog() == DialogResult.OK)
        {
            try
            {
                strPath = fd.FileName;
                string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"";
                OleDbConnection Con = new OleDbConnection(strCon);//建立连接
                string strSql = "select * from [Sheet1$]";//表名的写法也应注意不同,对应的excel表为sheet1,在这里要在其后加美元符号$,并用中括号
                OleDbCommand Cmd = new OleDbCommand(strSql, Con);//建立要执行的命令
                OleDbDataAdapter da = new OleDbDataAdapter(Cmd);//建立数据适配器
                DataSet ds = new DataSet();//新建数据集
                da.Fill(ds, "sheet1");//把数据适配器中的数据读到数据集中的一个表中(此处表名为sheet1,可以任取表名)
                //指定datagridview1的数据源为数据集ds的第一张表(也就是sheet1表),也可以写ds.Table["sheet1"]

                dataGridView1.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);//捕捉异常
            }
        }
    }
相关推荐
刘_sy7 小时前
使用EasyExcel和多线程实现高效数据导出
java·excel·easyexcel·批量导出excel
浅陌sss9 小时前
Xlua中C#引用Lua变量,导致Lua侧的GC无法回收的原因及解决方法
c#·lua
棉晗榜9 小时前
c#模拟鼠标点击左键
c#
爱吃香蕉的阿豪11 小时前
在c#中虚方法和抽象类的区别
深度学习·c#·.netcore
PowerBI学谦12 小时前
Copilot:Excel中的Python高级分析来了
python·excel·copilot
晚秋大魔王13 小时前
C# 添加图标
c#·visual studio code
shepherd枸杞泡茶13 小时前
第3章 .NETCore核心基础组件:3.1 .NET Core依赖注入
开发语言·c#·.net·.netcore
yuanpan14 小时前
C#的async异步方法里如果使用了await,那么它跟同步方法有什么区别?
开发语言·c#
CodeCraft Studio17 小时前
.NET版PDF处理控件Aspose.PDF教程:在 C# 中将 TIFF 文件转换为 PDF
pdf·c#·.net
斯内科17 小时前
C#使用文件读写操作实现仙剑五前传称号存档修改
c#·二进制·修改器