You are on page 1of 3

string connectionString =

"Provider=Microsoft.Jet.OleDb.4.0; Data Source=D:\MySamplefile.xls;


Extended Properties=Excel 8.0;"

using(OleDbConnection Connection =
new OleDbConnection(connectionString))

{

Connection.Open()

using(OleDbCommand command =
new OleDbCommand())

{

command.Connection = Connection;

command.CommandText = "CREATE TABLE
[EmpTable$](EmpFirstName Char(100), EmpLastName char(100), EmpDept
char(250))";

command.ExecuteNonQuery();

}

//Add values to the table (EMPTable) in the Worksheet

using(OleDbCommand command =
new OleDbCommand())

{

command.Connection = Connection;

command.CommandText = "INSERT INTO TABLE
[EmpTable$](EmpFirstName ,EmpLastName ,EmpDept )
VALUES('Karthik','Anbu','karthik.Anbu@xyz.com')";

command.ExecuteNonQuery();

command.CommandText = "INSERT INTO TABLE
[EmpTable$](EmpFirstName ,EmpLastName ,EmpDept )
VALUES('Arun','Kumar','Arun.Kumar@xyz.com')";

command.ExecuteNonQuery();

}
Code : Reading data from Excel sheet
DataTable dt;

string connectionString =
"Provider=Microsoft.Jet.OleDb.4.0; Data Source=D:\MySamplefile.xls;
Extended Properties=Excel 8.0;"

using(OleDbConnection Connection =
new OleDbConnection(connectionString))

{

Connection.Open()

using(OleDbCommand command =
new OleDbCommand())

{

command.Connection = Connection;

command.CommandText = "SELECT * FROM
[EmpTable]";

using(OleDbDataAdapter adapter =new OleDbDataAdapter())
{
adapter.SelectCommand = command;
adapter.Fill(dt);
}
}
}

Conclusion:
So in this article we have seen how to do a small manipulation of reading and wr
iting Excel data using C# which we normally require in our day-to-day coding.
-----------------------------------------------------------------------
public static void ExcelExport(DataTable data, String fileName, bool openAfter)
{
//export a DataTable to Excel
DialogResult retry = DialogResult.Retry;
while (retry == DialogResult.Retry)
{
try
{
using (ExcelWriter writer = new ExcelWriter(fileName))
{
writer.WriteStartDocument();
// Write the worksheet contents
writer.WriteStartWorksheet("Sheet1");
//Write header row
writer.WriteStartRow();
foreach (DataColumn col in data.Columns)
writer.WriteExcelUnstyledCell(col.Caption);
writer.WriteEndRow();
//write data
foreach (DataRow row in data.Rows)
{
writer.WriteStartRow();
foreach (object o in row.ItemArray)
{
writer.WriteExcelAutoStyledCell(o);
}
writer.WriteEndRow();
}
// Close up the document
writer.WriteEndWorksheet();
writer.WriteEndDocument();
writer.Close();
if (openAfter)
OpenFile(fileName);
retry = DialogResult.Cancel;
}
}
catch (Exception myException)
{
retry = MessageBox.Show(myException.Message, "Excel Export", Message
BoxButtons.RetryCancel, MessageBoxIcon.Asterisk);
}
}
}

You might also like