/ / Ho bisogno di inserire i dati in Excel [chiuso] - c #

Ho bisogno di inserire i dati in Excel [chiuso] - c #

Devo inserire i dati in Excel usando C #.

Ho scritto il codice ma non l'aggiunta

try
{
string ConStr = "";
//getting the path of the file
string path = @"F:DataVendingItems.xlsx";
//connection string for that file which extantion is .xlsx
ConStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);
//making query
string query = "INSERT INTO [Sheet1$]([Coke],[Fanta],[Sprite],[Pepsi],[Necto],[CokePrice],[FantaPrice],[SpritePrice],[PepsiPrice],[NectoPrice]) VALUES("" + textBox1.Text + "","" + textBox2.Text + "","" + textBox3.Text + "","" + textBox4.Text + "","" + textBox5.Text + "","" + textBox6.Text + "","" + textBox7.Text + "","" + textBox8.Text + "","" + textBox9.Text + "","" + textBox10.Text + "")";
//Providing connection


OleDbConnection conn = new OleDbConnection(ConStr);

//checking that connection state is closed or not if closed the
//open the connection
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
//create command object
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]");
cmd.Connection = conn;
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Successfully Added");
}
conn.Close();
}


catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

risposte:

1 per risposta № 1

Stai solo eseguendo un SELECT * FROM [Sheet1 $] la tua query che non esegue mai effettivamente (che contiene l'inserto SQL). Quindi non stai mai inserendo i dati, prova a cambiare:

OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]")

A:

OleDbCommand cmd = new OleDbCommand(query)

Inoltre potresti cambiare:

OleDbConnection conn = new OleDbConnection(ConStr);

A:

using (OleDbConnection conn = new OleDbConnection(ConStr))
{
//create command object
using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]"))
{
cmd.Connection = conn;
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Successfully Added");
}
}
}

Poiché questo implementa IDisposable, in questo modo non sarà necessario verificare se la connessione è chiusa. E non dovrai chiudere la connessione.