/ / Preciso inserir os dados no Excel [fechado] - c #

Preciso inserir os dados no Excel [closed] - c #

Eu preciso inserir os dados no Excel usando c #.

Eu escrevi o código, mas não adicionei

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);
}

Respostas:

1 para resposta № 1

Você está executando apenas um SELECT * FROM [Sheet1 $] sua consulta que nunca está executando (que contém o Insert SQL). Para que você nunca esteja inserindo os dados, tente alterar:

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

Para:

OleDbCommand cmd = new OleDbCommand(query)

Também você pode mudar:

OleDbConnection conn = new OleDbConnection(ConStr);

Para:

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");
}
}
}

Como isso implementa o IDisposable, dessa forma, você não precisará verificar se a conexão está fechada. E você não precisará fechar a conexão.