插入dateTimePicker值以exceldate单元格在C#中使用OLE DB

我正在写我的第一个程序,一个数据库,而我坚持要插入一行新的信息到我的Excel数据库文件。 问题是每行数据在A列中都有一个date单元格。 我希望能够在dateTimePicker中select一个date,通过文本框input我的其他数据(名称,工作号码等),然后点击button,将所有数据插入到新行中。 我可以用Interop来完成,但是我不喜欢它,因为它打开了excel,需要很长时间。 我目前的代码适用于所有的文本框input,但不适用于date。 我的Excel文件中的date列是“date”格式。

所以我的问题是,我可以使用OLE DB插入一个dateTimePicker值到date格式的Excel单元格?

这是我的代码,非常感谢帮助。

private void button1_Click(object sender, EventArgs e) { if (label60.Text == "new") { 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.ACE.OLEDB.12.0;Data Source=C:\\Users\\Declan\\Documents\\Declan\\output.xlsx;Extended Properties=\"Excel 8.0;HDR=Yes;\" "); MyConnection.Open(); myCommand.Connection = MyConnection; DateTime date1 = dateTimePicker1.Value; string post1 = textBox3.Text; string type1 = textBox4.Text; string source1 = textBox5.Text; string income1 = textBox6.Text; string prof1 = textBox7.Text; string jobnum1 = textBox8.Text; sql = "Insert into [Database$] (date,postcode,type,source,income,profession,customerid) values('" + date1 + "','" + post1 + "','" + type1 + "','" + source1 + "','" + income1 + "','" + prof1 + "','" + jobnum1 + "')"; myCommand.CommandText = sql; myCommand.ExecuteNonQuery(); MyConnection.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } label60.Text = "edit"; } } 

对于那些感兴趣的我已经改变了使用oledb参数的代码。 不知道这是如何修复它,但看起来像Exceldate列需要采取格式dd / MM / yyyy的string

  private void button1_Click(object sender, EventArgs e) { if (label60.Text == "new") { try { System.Data.OleDb.OleDbConnection MyConnection; System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand(); MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Declan\\Documents\\Declan\\output.xlsx;Extended Properties=\"Excel 8.0;HDR=Yes;\" "); MyConnection.Open(); myCommand.Connection = MyConnection; DateTime date1 = dateTimePicker1.Value; string date2 = date1.ToString("dd/MM/yyyy"); myCommand.CommandText = "Insert into [Database$] ([date],postcode,type,source,income,profession,phonenumber) values(@date, @post, @type,@source,@income,@prof,@jobnum)"; myCommand.Parameters.AddWithValue("@date",date2); myCommand.Parameters.AddWithValue("@post", textBox3.Text); myCommand.Parameters.AddWithValue("@type", textBox4.Text); myCommand.Parameters.AddWithValue("@source", textBox5.Text); myCommand.Parameters.AddWithValue("@income", textBox6.Text); myCommand.Parameters.AddWithValue("@prof", textBox7.Text); myCommand.Parameters.AddWithValue("@jobnum", textBox8.Text); myCommand.ExecuteNonQuery(); MyConnection.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } label60.Text = "edit"; } }