Click here to Skip to main content
11,417,750 members (45,700 online)
Click here to Skip to main content
Add your own
alternative version

DataTable to Excel

, 15 Apr 2007 MIT
A quick and easy way to format and export a DataTable to an Excel spreadsheet
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace ExcelTest
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();

			data.Stats.AddStatsRow("bob", 15, "red");
			data.Stats.AddStatsRow("sjraphael", -0, "light urple");
			data.Stats.AddStatsRow("sconnery", 493, "fuschia");

			textBox1.Text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.xls");
		}

		private void button1_Click(object sender, EventArgs e)
		{
			// create the DataGrid and perform the databinding
			System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
			grid.HeaderStyle.Font.Bold = true;
			grid.DataSource = data;
			grid.DataMember = data.Stats.TableName;

			grid.DataBind();

			// render the DataGrid control to a file
			using(StreamWriter sw = new StreamWriter(textBox1.Text))
			{
				using(HtmlTextWriter hw = new HtmlTextWriter(sw))
				{
					grid.RenderControl(hw);
				}
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License

Share

About the Author

Jacob Klint
Software Developer
United States United States
No Biography provided

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150427.4 | Last Updated 15 Apr 2007
Article Copyright 2007 by Jacob Klint
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid