Sometimes we may require to generate Excel file from our reports,read from excel files to import data etc. This can be achieved using Office Interop (Office Automation) assemblies, but Office Automation in Web servers,got some issues;(More details: http://support.microsoft.com/kb/257757). The alternative is using OleDb provider. You may need to add one more attribute to connection string to connect to the Excel file. And connection string will be
string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=C:\Sample.xls; Extended Properties=Excel 8.0;" |
Please note the “Extended Properties” attribute. This attribute helps us to query the excel file.
Exporting Data from Data Table to Excel File.
string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=C:\Sample.xls; Extended Properties=Excel 8.0;" |
using (OleDbConnection Connection = new OleDbConnection(connectionString)) |
using (OleDbCommand command = new OleDbCommand()) |
command.Connection = Connection; |
command.CommandText = "CREATE TABLE [Sample$](FirstName Char(255), LastName char(255), Email char(255))" ; |
command.ExecuteNonQuery(); |
using (OleDbCommand command = new OleDbCommand()) |
command.Connection = Connection; |
command.CommandText = "INSERT INTO TABLE [Sample$](FirstName,LastName,Email) VALUES('Anuraj','P','[email protected]')" ; |
command.ExecuteNonQuery(); |
command.CommandText = "INSERT INTO TABLE [Sample$](FirstName,LastName,Email) VALUES('sreekumar','vn','[email protected]')" ; |
command.ExecuteNonQuery(); |
Import the Data from Excel
string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=C:\Sample.xls; Extended Properties=Excel 8.0;" |
using (OleDbConnection Connection = new OleDbConnection(connectionString)) |
using (OleDbCommand command = new OleDbCommand()) |
command.Connection = Connection; |
command.CommandText = "SELECT * FROM [Sample]" ; |
using (OleDbDataAdapter adapter = new OleDbDataAdapter()) |
adapter.SelectCommand = command; |