将Excel导入DataGridView [英] Importing Excel into DataGridView

查看:104
本文介绍了将Excel导入DataGridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个将两个数据库合并在一起的程序....我可以使用以下代码将Excel电子表格导入到DataGridView中:

I'm making a program where two databases are merged together.... I can import an excel spreadsheet into a DataGridView with this code:

     string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test.xls;Extended Properties=""Excel 8.0;HDR=YES;IMEX=1""";

                DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");

                DbDataAdapter adapter = factory.CreateDataAdapter();

                DbCommand selectCommand = factory.CreateCommand();
                selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";

                DbConnection connection = factory.CreateConnection();
                connection.ConnectionString = connectionString;

                selectCommand.Connection = connection;

                adapter.SelectCommand = selectCommand;

                data = new DataSet();

                adapter.Fill(data);

                dataGridView1.DataSource = data.Tables[0].DefaultView;

我遇到的问题是我试图找到一种方法来将源文件更改为对话框返回的路径.我有一个包含文件路径的字符串文件.如何将其合并到连接字符串中?

The problem I'm having is that I'm trying to find a way to change the source file to path that is returned by a dialog box. I have a string file that contains the file path. How do I incorporate this into the connection string?

或者也许有一种更好的方法呢?

Or maybe there is an altogether better way to do this?

谢谢!

卢克

推荐答案

使用 OleDbConnectionStringBuilder 类修改您的连接字符串.

Use the OleDbConnectionStringBuilder class to modify your connection string.

string fileName = "your path to the excel.xls"; // From the dialog box.

OleDbConnectionStringBuilder connStringBuilder =
    new OleDbConnectionStringBuilder();

connStringBuilder.DataSource = fileName;  // Set path to excel file
connStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=YES;IMEX1");        

...

// Get the connection string from the builder.
connection.ConnectionString = connStringBuilder.ConnectionString; 

这篇关于将Excel导入DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆