把Excel中的数据写入到dataGridView中

//单击命令按钮触发此事件
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();//首先根据打开文件对话框,选择excel表格
fd.Filter = "表格|.xls";//打开文件对话框筛选器
string strPath;//文件完整的路径名
if (fd.ShowDialog() == DialogResult.OK)
{
try
{
strPath = fd.FileName;
string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";//Office 07版本以上
// string strCon = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";//Office 07版本以下
OleDbConnection Con = new OleDbConnection(strCon);//建立连接
string strSql = "select
from [公司库存$]";//表名的写法也应注意不同,对应的excel表为sheet1,在这里要在其后加美元符号$,并用中括号
OleDbCommand Cmd = new OleDbCommand(strSql, Con);//建立要执行的命令
OleDbDataAdapter da = new OleDbDataAdapter(Cmd);//建立数据适配器
DataSet ds = new DataSet();//新建数据集
da.Fill(ds, "shyman");//把数据适配器中的数据读到数据集中的一个表中(此处表名为shyman,可以任取表名)
//指定datagridview1的数据源为数据集ds的第一张表(也就是shyman表),也可以写ds.Table["shyman"]
dataGridView1.DataSource = null;
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);//捕捉异常
}
}
}
}

猜你喜欢

转载自www.cnblogs.com/zhujie-com/p/12065687.html