怎么将excel数据导入到datagridview中
本人小白,想要實現EXCEL文件中的數據導入到datagridview中,EXCEL中的數據是多行多列,行數和列數不確定,如何實現導入到datagridview中顯示,具體的界面如下:
兩個button,選擇文件button實現選擇Excel文件的功能,并在textbox中顯示文件路徑;button2實現讀取數據到datagridview。
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;
namespace?Datagridview_Exceltest
{
?
?public?partial?class?Form1?:?Form
????{
????????public?Form1()
????????{
????????????InitializeComponent();
????????}
????????private?void?button1_Click(object?sender,?EventArgs?e)
????????{
????????????this.openFileDialog1.ShowDialog();
????????????this.textBox1.Text?=?this.openFileDialog1.FileName;
????????}
????????private?void?button2_Click(object?sender,?EventArgs?e)
????????{
???????????string?fileName?=?"";
???????????fileName?=?this.textBox1.Text;
???????????if?(this.textBox1.Text?!=?"")
???????????{
???????????????try
???????????????{
???????????????????string?strCon?=?"?Provider?=?Microsoft.Jet.OLEDB.4.0?;?Data?Source?=?"?+?fileName?+?"?;Extended?Properties=Excel?8.0";
???????????????????System.Data.OleDb.OleDbConnection?myConn?=?new?System.Data.OleDb.OleDbConnection(strCon);
???????????????????string?strCom?=?"?SELECT?*?FROM?[punishCase$]?";
???????????????????System.Data.OleDb.OleDbDataAdapter?myCommand?=?new?System.Data.OleDb.OleDbDataAdapter(strCom,?myConn);
???????????????????System.Data.DataTable?dt?=?new?System.Data.DataTable();
???????????????????myCommand.Fill(dt);
???????????????????this.dataGridView1.DataSource?=?dt;
???????????????????
???????????????}
???????????????catch
???????????????{
???????????????????MessageBox.Show("請選擇案件導入的EXCEL");
???????????????}
?????????????
???????????????
??????????????
???????????}
???????????else
???????????{
???????????????MessageBox.Show("請選擇Excel文件");
???????????}
????????}
????}
}
總結
以上是生活随笔為你收集整理的怎么将excel数据导入到datagridview中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新手必须掌握的学车技巧-上坡起步
- 下一篇: 论述HTML5平台的若干重要特性