在c#.net中逐一读取excel文件
我是新来的c#.net
我有Excel表,我想导入到database
。
我想逐个阅读它,并希望在database
插入值。
this.openFileDialog1.FileName = "*.xls"; DialogResult dr = this.openFileDialog1.ShowDialog(); if (dr == System.Windows.Forms.DialogResult.OK) { string path = openFileDialog1.FileName; string connectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=no;IMEX=1;""", openFileDialog1.FileName); string query = String.Format("select * from [{0}$]", "Sheet3"); OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString); DataSet dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView1.DataSource = dataSet.Tables[0];
我假设你在你的问题中执行代码后,你可以看到dataGridView1
的值。
当调用dataAdapter.Fill
时,Excel工作表中的实际读数就完成了。 所以,在你的情况下,读取单元格归结为索引dataSet.Tables[0]
列和行。
例如:
for (int row = 0; row < dataSet.Tables[0].Rows.Count; row++) { DataRow r = dataSet.Tables[0].Rows[row]; }
访问行r
的单元格是微不足道的(就像上面的示例,仅针对单元格)。
编辑
我忘了描述“将值插入数据库”部分。 我假设数据库是SQL Server(也可能是Express版本)。
首先:创build一个数据库连接。 而不是手动组成连接string,使用SqlConnectionStringBuilder
:
SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder(); csb.DataSource = <your server instance, eg "localhost\sqlexpress">; csb.InitialCatalog = <name of your database>; csb.IntegratedSecurity = <true if you use integrated security, false otherwise>; if (!csb.IntegratedSecurity) { csb.UserId = <User name>; csb.Password = <Password>; }
然后,使用连接string创build并打开一个新的SqlConnection
:
using (SqlConnection conn = new SqlConnection(csb.ConnectionString)) { conn.Open();
遍历所有要插入的值并执行相应的插入命令:
for (...) { SqlCommand cmd = new SqlCommand("INSERT INTO ... VALUES (@param1, ..., @paramn)", conn); cmd.Parameters.AddWithValue("@param1", value1); ... cmd.Parameters.AddWithValue("@paramn", valuen); cmd.ExecuteNonQuery(); }
这将closures连接,当using
块结束时:
}
你去了。 或者,您可以使用带有特殊插入命令的数据适配器。 然后,插入这些值将会变成单行,但是,您的数据库表格必须与Excel表单(分别为:您在发布的代码中获得的数据表格)具有相同的结构。
检查NPOI
这是Apache的POI Excel实现的.NET版本。 它可以轻松地完成你所需要的工作,并且有助于避免使用Jet提供程序时会遇到的一些问题(即Excel的本地副本,或者更糟糕的是服务器上Excel的副本)。