利用Ado.net来读取用户所指定的excel数据
2010-12-25 08:33
429 查看
利用Ado.net来读取用户所指定的excel数据,并将这些数据在DataGridView中显示出来!
基本思路为:
1.使用OpenFileDialog让用户打开excel文件,这里我使用OpenFileDialog.Filter属性对用户需要打开的文件类型进行了过滤
2.利用OleDbConnection连接到用户所指定的excel文件
3.利用OleDbCommand命令读取excel文件中的数据
4.将数据储存到OleDbDataAdapter中,并是用Fill属性将数据填充到DataTable中。
5.将DataGrid的数据源绑定到table中即可
下面是和具体实现的代码:
写道private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "Microsoft Excel files (*.xls)|*.xls";//指定打开文件的内型
string fileName;
string connectionString;
if (fileDialog.ShowDialog() == DialogResult.OK) {
fileName = fileDialog.FileName;
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;'";
OleDbConnection con = new OleDbConnection(connectionString);//连接到指定的Excel文件
con.Open();
string strSQL = "SELECT * FROM [Sheet1$]";
OleDbCommand command=new OleDbCommand(strSQL,con);
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
DataTable table=new DataTable();
adapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.DataSource = bindingSource1;
con.Close();
adapter.Dispose();
}
基本思路为:
1.使用OpenFileDialog让用户打开excel文件,这里我使用OpenFileDialog.Filter属性对用户需要打开的文件类型进行了过滤
2.利用OleDbConnection连接到用户所指定的excel文件
3.利用OleDbCommand命令读取excel文件中的数据
4.将数据储存到OleDbDataAdapter中,并是用Fill属性将数据填充到DataTable中。
5.将DataGrid的数据源绑定到table中即可
下面是和具体实现的代码:
写道private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "Microsoft Excel files (*.xls)|*.xls";//指定打开文件的内型
string fileName;
string connectionString;
if (fileDialog.ShowDialog() == DialogResult.OK) {
fileName = fileDialog.FileName;
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;'";
OleDbConnection con = new OleDbConnection(connectionString);//连接到指定的Excel文件
con.Open();
string strSQL = "SELECT * FROM [Sheet1$]";
OleDbCommand command=new OleDbCommand(strSQL,con);
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
DataTable table=new DataTable();
adapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.DataSource = bindingSource1;
con.Close();
adapter.Dispose();
}
相关文章推荐
- ADO.NET实现Excel数据的读取
- ADO.NET数据库编程 利用应用程序配置文件进行数据的读取
- 利用QTP调用外部VBS方法读取指定Excel数据的方法
- 从Excel中指定的sheet名称或索引读取数据到DataTable,以便用户更改sheet名称后仍能读取数据
- ASP.Net中利用OLE读取Excel数据源时,报“未指定的错误”的错误解决办法
- 用ADO.NET从Excel文件中读取数据
- C#利用ADO.NET技术读取Excel
- 使用ADO.NET的DbProviderFactory读取或写入Excel中的表单
- Ado.Net读取Excel常见问题总结
- ADO.NET中的多数据表操作浅析之读取
- 使用ADO.net转换数据到Excel格式并提供下载
- ADO.NET 如何读取 Excel
- ADO.NET基础实战 从文件读取数据插入到数据库
- asp.net读取Excel数据
- POI读取Excel数据保存到数据库,并反馈给用户处理信息
- VBA:Excel 中利用 ADO 查询数据
- ADO.NET中的多数据表操作浅析之读取
- ADO.NET 如何读取 Excel (上)
- 利用ADO.NET SqlBulkCopy 大批量快速导入数据
- 使用ADO.net转换数据到Excel格式并提供下载