C# 连接EXCEL 文本框保存输入信息

部分代码:

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

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

        private void button1_Click(object sender, EventArgs e)
        {
            string Path = textBox1.Text.Trim();
            string sql = textBox2.Text.Trim();
            //string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
            string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
            OleDbConnection conn = new OleDbConnection(connStr);
            conn.Open();
            OleDbDataAdapter myCommand = null;
            DataSet ds = null;
            myCommand = new OleDbDataAdapter(sql, connStr);
            ds = new DataSet();
            myCommand.Fill(ds, "table1");

            dataGridView1.DataSource = ds.Tables[0];
            //dataGridView1.Columns["username"].Visible = false;
            //dataGridView1.RowHeadersVisible = false;
            //button2.Enabled = false;
            dataGridView1.Columns["UserId"].ReadOnly = true;
            conn.Close();
        }

     

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = Properties.Settings.Default.defaultPath;
            textBox2.Text = Properties.Settings.Default.defaultSQL;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.defaultPath = textBox1.Text.Trim();
            Properties.Settings.Default.defaultSQL = textBox2.Text.Trim();
            Properties.Settings.Default.Save();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string msg = string.Format("第{0}行,第{1}列", dataGridView1.CurrentCell.RowIndex,
                dataGridView1.CurrentCell.ColumnIndex);
            richTextBox1.Text = msg+"\n值为:"+dataGridView1.CurrentCell.Value.ToString();
        }
    }
}

 

posted @ 2023-04-30 12:57  竹楼风雨声  阅读(27)  评论(0编辑  收藏  举报