Upload
aksharma36
View
226
Download
0
Embed Size (px)
Citation preview
8/12/2019 Reading Filees
1/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), EmpDeptchar(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','[email protected]')";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO TABLE[EmpTable$](EmpFirstName ,EmpLastName ,EmpDept )VALUES('Arun','Kumar','[email protected]')";
command.ExecuteNonQuery();
}
Code : Reading data from Excel sheetDataTable 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))
8/12/2019 Reading Filees
2/3
{
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 writing 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);
8/12/2019 Reading Filees
3/3
} 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", MessageBoxButtons.RetryCancel, MessageBoxIcon.Asterisk); } }}