当前位置: 首页 > 图文教程 > .Net技术 > ADO.NET > ADO.Net读取Excel中的数据

ADO.NET
ADO.NET:小编谈ADO.NET中窗体的飘动
ADO.NET:利用IC卡制作考勤程序
ADO.NET:小编谈如何实现滚动字幕
Remoting笔记:错误:“由于安全限制,无法访问类型System.RunTime.Remoting.ObjRef”

ADO.NET 中的 ADO.Net读取Excel中的数据


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 266 ::
收藏到网摘: n/a

今天做了利用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();
}