ADO.Net读取Excel中的数据

作者在 2009-05-05 20:09:52 发布以下内容

今天做了利用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();
}
.Net | 阅读 2082 次
文章评论,共0条
游客请输入验证码
浏览46281次
最新评论