Reputation: 9
hello I need to make a connection to an excel file to do an update of a column I have this code
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());
}
}
}
}
but something is not working, when I run it opens the connection
I can do??? please, thanks!
Upvotes: 0
Views: 8121
Reputation: 216243
Some errors spotted in the connection string above:
Change the connection string in this way:
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\farm.xls';'Extended Properties=Excel 8.0;HDR=YES'");
If your Excel file has not an header as first line then the whole query changes because you cannot use the name
and COMERCIO
as columns name. Instead you need to use the letter F followed by the column number (as set F1 = 'FARM GDL' where F2 like '...'
)
Upvotes: 3