您的位置:首页 > 其它

利用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();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: