关于EXCEL表如何导入进DataGridView控件中的问题

来源:互联网 发布:讲故事软件哪个好 编辑:程序博客网 时间:2024/05/22 13:31

之前做这个东西的时候,在网上搜了不少代码,可是发现许多代码都不能完整的运行,总是有各种各样的错误,让人好生烦恼,今天终于写出来了,与大家分享。

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data.OleDb;using System.IO;namespace WindowsFormsApplication2{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private DataSet thisDataSet = null;        private void button1_Click(object sender, EventArgs e)        {            try            {                string str=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+textBox1.Text+";Extended Properties=Excel 8.0";                OleDbConnection myConn = new OleDbConnection(str);                myConn.Open();                OleDbDataAdapter thisAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", myConn);                //OleDbCommandBuilder thisBuilder = new OleDbCommandBuilder(thisAdapter);                thisDataSet = new DataSet();                thisAdapter.Fill(thisDataSet, "ExcelInfo");                this.dataGridView1.DataSource = thisDataSet.Tables[0];                myConn.Close();            }            catch (OleDbException ex)            {                MessageBox.Show(ex.Message);            }        }        private void button2_Click(object sender, EventArgs e)        {            if (openFileDialog1.ShowDialog() == DialogResult.OK)            {                textBox1.Text = openFileDialog1.FileName;                FileInfo finfo = new FileInfo(textBox1.Text);                string strName = finfo.FullName;                textBox1.Text = strName;            }        }    }    }


原创粉丝点击