Click here to Skip to main content
15,882,163 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Hi,

am inserting data into excel when the card is swiped,am using oledb connection
my code is :
<pre lang="xml">private string GetConnectionString()
       {
           Dictionary<string, string> props = new Dictionary<string, string>();

           // XLSX - Excel 2007, 2010, 2012, 2013
           props["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
           props["Extended Properties"] = "Excel 12.0 XML";
           props["Data Source"] = "C:\\MyExcel.xlsx";

         
           StringBuilder sb = new StringBuilder();

           foreach (KeyValuePair<string, string> prop in props)
           {
               sb.Append(prop.Key);
               sb.Append('=');
               sb.Append(prop.Value);
               sb.Append(';');
           }

           return sb.ToString();
       }</pre>

and inserting data code in button click is:
C#
string connectionString = GetConnectionString();

 using (OleDbConnection conn = new OleDbConnection(connectionString))
 {
     conn.Open();
     OleDbCommand cmd = new OleDbCommand();
     cmd.Connection = conn;

     //cmd.CommandText = "CREATE TABLE [table1] (id INT);";
     //cmd.ExecuteNonQuery();

     cmd.CommandText = "INSERT INTO [sheet1$](id) VALUES(" + newString + ");";
     cmd.ExecuteNonQuery();

     conn.Close();
 }


here newString variable contains data as string "0008478660" but in excel it's inserting as "8478660" . how insert complete string as it is, with zero's
Posted

by giving single quotes, otherwise it will consider as number.
C#
cmd.CommandText = "INSERT INTO [sheet1$](id) VALUES('" + newString + "');";
 
Share this answer
 
v2
Comments
Maciej Los 3-May-14 4:15am    
5ed!
DamithSL 3-May-14 4:18am    
Thanks @Maciej Los
Because it's numeric data, EXcel formats it as a number - just as it would when if you typed it.
You can override that:
C#
cmd.CommandText = "INSERT INTO [sheet1$](id) VALUES('" + newString + "');";
To force Excel to treat it as a string art all times.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900