C#Excel连接

你好我需要连接到一个Excel文件来做一个列的更新我有这个代码

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; namespace Excel { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnUpdate_Click(object sender, EventArgs e) { try { System.Data.OleDb.OleDbConnection MyConnection; System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand(); string sql = null; MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\farm.xls';Extended Properties=Excel 8.0;"); MyConnection.Open(); myCommand.Connection = MyConnection; sql = "Update [Sheet1$] set name = 'FARM GDL' where COMERCIO like 'FARM GUADALAJARA'"; myCommand.CommandText = sql; myCommand.ExecuteNonQuery(); MyConnection.Close(); MessageBox.Show("Success"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } } 

但有些东西是不行的,当我运行它打开连接

我可以??? 拜托,谢谢!

在上面的连接string中发现一些错误:

以这种方式更改连接string:

 MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\farm.xls';'Extended Properties=Excel 8.0;HDR=YES'"); 
  1. \字符具有特殊的含义,需要在pathstring中加倍或者以@为前缀的整个string
  2. 如果您的Excel文件在第一行中包含标题,则应将其添加到连接stringHDR = YES;
  3. 扩展属性应该用单引号括起来

如果您的Excel文件没有标题作为第一行,那么整个查询将更改,因为您不能使用nameCOMERCIO作为列名称。 相反,您需要使用字母F,后跟列号(如set F1 = 'FARM GDL' where F2 like '...'