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);//捕捉异常
            }
        }
    }
相关推荐
李高钢2 小时前
C# WinForms 架构与项目实战:多窗体通信、三层架构、数据库、日志与配置
架构·c#·winforms
码云数智-园园4 小时前
Python如何将律师的Excel噩梦变成自动化系统
python·自动化·excel
OPEN-F4 小时前
Python进阶教程:自动化办公实战
python·c#·自动化
用户298698530145 小时前
将 Excel 表格转换为图片的三种实用方法
人工智能·后端·excel
czhc11400756635 小时前
C# 处理体数据:装、钉、交、取消
c#
淡海水6 小时前
03-03-线性-LinkedList-T-源码不变式与选择边界
windows·链表·c#·编译·linkedlist·clr·机器码
AI英德西牛仔6 小时前
秘塔 导出word指令之外:AI导出鸭电脑版的底层逻辑与批量交付哲学
人工智能·word·excel·deepseek·ai导出鸭
AI英德西牛仔7 小时前
让 AI 导出回归优雅:纳米AI excel 与“AI 导出鸭”的 PC 端批量导出技术拆解
人工智能·excel·deepseek·ai导出鸭
AI导出鸭7 小时前
怎么让腾讯元宝做表格?AI导出鸭苹果版通过解析引擎将元宝表格HTML转为结构化数据,一键导出标准Excel或Word
人工智能·chatgpt·html·excel·ai导出鸭
longxiaozhang621 小时前
C# Array类:数组其实没那么难
开发语言·c#