简体   繁体   中英

C# Excel Connection

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!

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'"); 
  1. The \\ character has special meaning and need to be doubled in path strings or the whole string prefixed with @
  2. if your Excel File has an header in the first line you should add to the connection string HDR=YES;
  3. The Extended Properties should be enclosed in single quote

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 '...' )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM