本文主要是介绍怎么将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文件");
}
}
}
}
调用: EcxelToDataGridView(
"test.xls"
,dataGridView1);
/// Excel数据导入方法
public
void
EcxelToDataGridView(
string
filePath,DataGridView dgv)
{
//根据路径打开一个Excel文件并将数据填充到DataSet中
string
strConn =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = "
+ filePath +
";Extended Properties ='Excel 8.0;HDR=NO;IMEX=1'"
;
//HDR=YES 有两个值:YES/NO,表示第一行是否字段名,默认是YES,第一行是字段名
OleDbConnection conn =
new
OleDbConnection(strConn);
conn.Open();
string
strExcel =
""
;
OleDbDataAdapter myCommand =
null
;
DataSet ds =
null
;
strExcel =
"select * from [sheet1$]"
;
myCommand =
new
OleDbDataAdapter(strExcel, strConn);
ds =
new
DataSet();
myCommand.Fill(ds,
"table1"
);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
这篇关于怎么将excel数据导入到datagridview中的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!