我正在编写我的第一个程序,一个数据库,我不得不在我的excel数据库文件中插入一行新信息。问题是每行数据在A列中都有一个日期单元格。我希望能够在dateTimePicker中选择日期,通过文本框输入我的其余数据(名称,作业号等),然后在按钮上单击将所有数据插入新行。我可以使用Interop做到这一点,但我不喜欢它,因为它打开了excel并且耗时太长。我的代码目前适用于所有文本框输入,但不适用于日期。我的Excel文件中的日期列采用“日期”格式。
所以我的问题是,我可以使用OLE DB将dateTimePicker值插入日期格式化的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";
}
}
答案 0 :(得分:0)
对于那些感兴趣的人,我已经将代码更改为使用oledb参数。不知道这是如何解决的,但看起来像采用格式为dd / MM / yyyy的字符串所需的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();
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";
}
}