Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
How to export data table to excel in c# using Oledb?
I want to transfer data in data table to excel in c# using Oledb provider. I am able to insert few cells using below code:
C#
try
            {
                string filelocation = @"E:\Alex\Arab_Test_Oledb.xls";
                System.Data.OleDb.OleDbConnection MyConnection;
                System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
                string sql = null;
                //string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filelocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filelocation + ";Extended Properties=Excel 8.0;");

                MyConnection.Open();

                myCommand.Connection = MyConnection;

                sql = "Insert into [Sheet1$] (EMPLOYEE_ID,ADDRESS1) values('5','e')";

                myCommand.CommandText = sql;

                myCommand.ExecuteNonQuery();

                MyConnection.Close();

            }
            catch (Exception ex)
            {
                
            }


What I have tried:

My code is as below:
try
{
string filelocation = @"E:\Alex\Arab_Test_Oledb.xls";
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
//string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filelocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filelocation + ";Extended Properties=Excel 8.0;");

MyConnection.Open();

myCommand.Connection = MyConnection;

sql = "Insert into [Sheet1$] (EMPLOYEE_ID,ADDRESS1) values('5','e')";

myCommand.CommandText = sql;

myCommand.ExecuteNonQuery();

MyConnection.Close();

}
catch (Exception ex)
{

}
Posted
Updated 11-Jul-16 18:39pm
Comments
Suvendu Shekhar Giri 11-Jul-16 10:30am    
What is the issue here?
Ema112 11-Jul-16 11:31am    
No issue, i want to set it dynamically via a datatable

1 solution

 
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