C#上位机采用数据库操作方式对Excel或WPS表格进行读取操作

C#采用数据库操作方式对Excel或WPS表格进行读取操作

1、创建连接字符串并编写一个进行数据库操作的方法

csharp 复制代码
    public class OleDbHelper
    {
        //创建连接字符串
        private static string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};" +
            "Extended Properties='Excel 8.0;IMEX=1;HDR=YES'";

        /// <summary>
        /// 返回一个DataSet结果集
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <param name="path">excel文件路径</param>
        /// <returns></returns>
        public static DataSet GetDataSet(string sql, string path)
        {
            OleDbConnection conn = new OleDbConnection(string.Format(connString, path));
            OleDbCommand cmd = new OleDbCommand(sql, conn);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);

            DataSet ds = new DataSet();
            try
            {
                conn.Open();
                da.Fill(ds);
                return ds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }

2、编写SQL语句进行数据的查询并返回对象列表

我这里是从Excel读取指定列的数据string sql = "select 姓名,性别,出生日期,家庭住址 from [Student$]";

如果需要读取全部的数据string sql = "select * from [Student$]";

**[Student$]**这个表示这个Excel工作簿的名称为Student的工作表。

csharp 复制代码
    public class Student
    {
        public string StudentName { get; set; }
        public string Gender { get; set; }
        public DateTime Birthday { get; set; }
        public string Address { get; set; }
    }

存放数据的对象

csharp 复制代码
        public List<Student> GetStudentFromExcel(string path)
        {
            List<Student> stuList = new List<Student>();
            string sql = "select 姓名,性别,出生日期,家庭住址 from [Student$]";

            DataTable dt = OleDbHelper.GetDataSet(sql, path).Tables[0];

            foreach (DataRow row in dt.Rows)
            {
                stuList.Add(new Student()
                {
                    StudentName = row["姓名"].ToString(),
                    Gender = row["性别"].ToString(),
                    Birthday = Convert.ToDateTime(row["出生日期"]),
                    Address = row["家庭住址"].ToString()
                });
            }

            return stuList;
        }

3、将对象列表显示在界面上

csharp 复制代码
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            DialogResult result = openFileDialog.ShowDialog();
            string path = openFileDialog.FileName;
            this.dataGridView1.DataSource = objExcelRW.GetStudentFromExcel(path);
        }

4、效果展示


5、提示:如果需要DataGridView的列数少于需要展示的对象的属性数量,DataGridView会自动创建新的列。

csharp 复制代码
    public class Student
    {
        public string StudentName { get; set; }
        public string Gender { get; set; }
        public DateTime Birthday { get; set; }
        public string Address { get; set; }
        public string StudentIdNo { get; set; }
    }
csharp 复制代码
        public List<Student> GetStudentFromExcel(string path)
        {
            List<Student> stuList = new List<Student>();
            string sql = "select * from [Student$]";

            DataTable dt = OleDbHelper.GetDataSet(sql, path).Tables[0];

            foreach (DataRow row in dt.Rows)
            {
                stuList.Add(new Student()
                {
                    StudentName = row["姓名"].ToString(),
                    Gender = row["性别"].ToString(),
                    Birthday = Convert.ToDateTime(row["出生日期"]),
                    Address = row["家庭住址"].ToString(),
                    StudentIdNo = row["身份证号"].ToString()
                });
            }
            return stuList;
        }

Student类和public List<Student> GetStudentFromExcel(string path)方法进行上面修改,显示效果如下图:

如果此时还是想只显示自己所设定的列,可以直接在界面构造方法里面添加

csharp 复制代码
        public FrmMain()
        {
            InitializeComponent();

            this.dataGridView1.AutoGenerateColumns = false;//禁止自动生成列
        }

如果出现报错可以查看"未在本地计算机上注册"Microsoft.ACE.OLEDB.12.0"提供程序"的解决方案

相关推荐
eWidget18 小时前
随机森林原理:集成学习思想 —— Java 实现多棵决策树投票机制
java·数据库·随机森林·集成学习·金仓数据库
Traced back18 小时前
SQL Server 核心语法+进阶知识点大全(小白版)
数据库·sqlserver
资深web全栈开发18 小时前
PostgreSQL枚举还是字符串:ENUM vs VARCHAR + CHECK 的权衡
数据库·postgresql
凯子坚持 c18 小时前
C++基于微服务脚手架的视频点播系统---客户端(4)
数据库·c++·微服务
OceanBase数据库官方博客19 小时前
OceanBase场景解码系列三|OB Cloud 如何稳定支撑中企出海实现数 10 倍的高速增长?
数据库·oceanbase·分布式数据库
m0_5613596719 小时前
使用Python处理计算机图形学(PIL/Pillow)
jvm·数据库·python
山岚的运维笔记19 小时前
SQL Server笔记 -- 第14章:CASE语句
数据库·笔记·sql·microsoft·sqlserver
Data_Journal19 小时前
如何使用 Python 解析 JSON 数据
大数据·开发语言·前端·数据库·人工智能·php
ASS-ASH19 小时前
AI时代之向量数据库概览
数据库·人工智能·python·llm·embedding·向量数据库·vlm
xixixi7777719 小时前
互联网和数据分析中的核心指标 DAU (日活跃用户数)
大数据·网络·数据库·数据·dau·mau·留存率