/ / Excelにデータを挿入する必要があります[閉じる] - C#

私はExcelにデータを挿入する必要があります[閉鎖] - C#

C#を使用してExcelにデータを挿入する必要があります。

私はコードを書いたが、追加しない

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

回答:

回答№1は1

SELECT * FROM [Sheet1 $]を実際に実行していないクエリー(Insert SQLを含む)を実行するだけです。データを挿入していないので、変更してみてください:

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

に:

OleDbCommand cmd = new OleDbCommand(query)

また、変更することができます:

OleDbConnection conn = new OleDbConnection(ConStr);

に:

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

これはIDisposableを実装しているので、接続が閉じられているかどうかを確認する必要はありません。そして、接続を閉じる必要はありません。