将Excel数据导入c#的datagridview

时间:2022-01-08 03:18:53

//需要引入的命名空间

using System.Runtime.InteropServices;//获取鼠标事件

using System.IO;

using System.Data.OleDb;


//核心代码

private void button1_Click(object sender, EventArgs e)

{

OpenFileDialog ofd = new OpenFileDialog();//首先根据打开文件对话框,选择要打开的文件

ofd.Filter = "Excel表格|*.xlsx|Excel97-2003表格|*.xls|所有文件|*.*";//打开文件对话框筛选器,默认显示文件类型

string strPath;//定义文件路径

if (ofd.ShowDialog() == DialogResult.OK)

{

try

{

strPath = ofd.FileName;

//string sss = ofd.SafeFileName;//获取文件名称

string fileType = System.IO.Path.GetExtension(strPath);//获取文件的后缀

string strCon = "";

if (fileType == ".xls")//如果为97-2003格式文件

{

strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties=‘Excel 8.0;HDR=YES;IMEX=1‘";

}

else//如果为2007格式文件

{

strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+strPath+";Extended Properties=‘Excel 12.0;HDR=YES;IEMX=1‘";

}

OleDbConnection conn=new OleDbConnection(strCon);

Application.DoEvents();

string strSql = "select * from [Sheet1$]";

OleDbCommand Cmd= new OleDbCommand(strSql,conn);

OleDbDataAdapter da = new OleDbDataAdapter(Cmd);

DataSet ds = new DataSet();

da.Fill(ds,"插入表");

dataGridView1.DataSource=ds.Tables[0];

dataGridView1.AllowUserToAddRows = false;

dataGridView1.AllowUserToDeleteRows = false;

//MessageBox.Show(sss);


}

catch (Exception ex)

{


MessageBox.Show(ex.Message);//捕捉异常