你好我需要连接一个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());
}
}
}
}
但有些东西不起作用,当我运行它时会打开连接
我能做到吗???拜托,谢谢!答案 0 :(得分:3)
上面的连接字符串中发现了一些错误:
以这种方式更改连接字符串:
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\farm.xls';'Extended Properties=Excel 8.0;HDR=YES'");
如果您的Excel文件没有标题作为第一行,则整个查询会更改,因为您无法使用name
和COMERCIO
作为列名称。相反,您需要使用字母F后跟列号(作为set F1 = 'FARM GDL' where F2 like '...'
)