把Excel中的数据写入到dataGridView中

Posted zhujie-com

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了把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);//捕捉异常
}
}
}
}

以上是关于把Excel中的数据写入到dataGridView中的主要内容,如果未能解决你的问题,请参考以下文章

Winform excel导入问题

在C#中,如何把DataGridview中的数据导出到一个Excel表中

c#如何将html标签写入指定的excel中

把dataGridView数据保存到已有的Excel表中

C#读取Excel表格数据到DataGridView中和导出DataGridView中的数据到Excel

请问谁有C#datagridview导出csv格式的excel的代码啊,发一下学习学习?