Hi im unsing Oledb to insert data to an excel sheet from multiple textboxes. The issue i have is that it is not going into excel as a number type but string, so a grpah can no be automated off the date.
How would i insert values into excel as number type? ive tried converting the textboxes to int with no luck.
My code is as below.
string szConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=L://Metrics_gen.xlsx;Extended Properties='Excel 8.0;HDR=YES;'";
OleDbConnection conn = new OleDbConnection(szConn);
int v1 = Convert.ToInt32(textBox1.Text);
int v2 = Convert.ToInt32(textBox2.Text);
int v3 = Convert.ToInt32(textBox3.Text);
int v4 = Convert.ToInt32(textBox4.Text);
int v5 = Convert.ToInt32(textBox5.Text);
conn.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO [Sheet1$]([Total],[Closed],[Issues],[Cancelled],[Back out]) VALUES('" + v1 + "','" + v2 + "','" + v3 + "','" + v4 + "','" + v5 + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("complete");
The problem is that you are converting your integers into string literals when constructing the insert command. See below:
Change that line into:
This should solve all your problems 🙂
Note: Constructing SQL by hand is error prone. Integers are the least of your worries. Imagine trying to inserting a string which happens to contain the single quotation mark character (‘), a float when you have set your culture to one with comma as the decimals separator, a date and so on and so forth. Personally, I prefer using libraries such as EPPlus (XLSX) and ExcelLibrary (XLS). Both are LGPL licensed and give you greater flexibility than the method you are currently using. They do not require Excel to be installed on the machine which makes them ideal for server-side Excel report generation. Moreover they help avoid the various memory leak problems solutions using Microsoft Office Interop often come with.