Export DataTable to Excel/CSV using C#
I was working on a project and my client asked me to export data to excel or .csv file. do you know how easy is this, Just by using StreamWriter I exported a DataTable to excel .csv file.
and here is the code
for this article I used Northwind database and Employees table from MS SQL server.
private void ExportToExcel()
{
try
{
SqlConnection Con = new SqlConnection("Server=(local);Database=NorthWind; Integrated Security=TRUE");
Con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country FROM Employees"
, Con);
DataSet employees = new DataSet();
adapter.Fill(employees, "Employees");
string strSave = null;
foreach (DataColumn columns in employees.Tables["Employees"].Columns)
{
strSave += columns.ColumnName.ToString() + ",";
}
strSave = strSave.Substring(0, strSave.Length - 1) + Environment.NewLine;
foreach (DataRow dr in employees.Tables["Employees"].Rows)
{
strSave +=
dr["EmployeeID"].ToString() + "," +
dr["FirstName"].ToString() + "," +
dr["LastName"].ToString() + "," +
dr["Title"].ToString() + "," +
dr["Address"].ToString() + "," +
dr["City"].ToString() + "," +
dr["Region"].ToString() + "," +
dr["PostalCode"].ToString() + "," +
dr["Country"].ToString() + Environment.NewLine;
}
StreamWriter writer = new StreamWriter(@"C:\book1.csv");
writer.Write(strSave);
writer.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
At first I assigned all details from query to a database and looped over columns to get the columns and then looped over rows and concatenated whit the strSave variable and saved it in a path using StreamWriter
Wasn't it very easy.... ;)
2 Comments On This Entry
Page 1 of 1
Curtis Rutland
13 July 2011 - 06:39 AM
That's not really exporting to Excel. That's exporting to a CSV, which Excel can read. There is a difference.
Page 1 of 1
Trackbacks for this entry [ Trackback URL ]
Recent Entries
-
Export DataTable to Excel .CSV using C#.Net {How easy is this}on Jul 13 2011 05:00 AM
-
-
Search My Blog
0 user(s) viewing
0 Guests
0 member(s)
0 anonymous member(s)
0 member(s)
0 anonymous member(s)
Recent Comments
-
-
Curtis Rutland
on Jul 13 2011 06:39 AM
Export DataTable to Excel .CSV using C#.Net {How easy is this}
|
|



2 Comments









|