C# .net窗体实战11:ODBC数据库读取

题目:

界面:

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;//读取的是当下项目中debug中的路径
            string fileName = "数据表.xlsx";
            string filePath = Path.Combine(currentDirectory, fileName);
            //定义了连接到Excel文件的连接字符串
            string excelConnectionString = "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1';";
            //Provider=Microsoft.ACE.OLEDB.16.0:指定使用的OLEDB提供程序版本
            //Data Source=:指定数据源(Excel文件)的路径
            //Extended Properties='Excel 8.0;HDR=No;IMEX=1':定义Excel格式和数据读取选项。
            //HDR=No表示Excel文件第一行没有列名,IMEX=1确保以文本形式读取数据

            MessageBox.Show(filePath);
            //创建一个数据库连接对象,连接到Excel文件,并打开连接
            using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
            {
                connection.Open();
                //使用GetOleDbSchemaTable方法来获取Excel文件中的工作表名称,存储在sheetName变量中
                DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                string sheetName = dtSchema.Rows[0].Field<string>("TABLE_NAME");

                // 构建一个SQL查询语句,读取指定工作表的所有数据
                string selectQuery = "SELECT * FROM [" + sheetName + "]";
                using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectQuery, connection))
                {
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);//并用OleDbDataAdapter填充到DataTable对象中

                    listBox1.Items.Clear();
                    listBox2.Items.Clear();
                    listBox3.Items.Clear();
                    foreach (DataRow row in dt.Rows)
                    {
                        listBox1.Items.Add(row[0]);
                        listBox2.Items.Add(row[1]);
                        listBox3.Items.Add(row[2]);
                    }
                }

            }
        }
    }
}

重点在于如何读取excel表格三列数据,并在listBox中显示出来,整体上的逻辑就是,先连接数据库,成功之后进行读取,然后对读取的数据进行处理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值