Home arrow GIS Data & Resources arrow Scripts and Code arrow C# Code arrow C# Convert ADO.NET DataTable to Excel Spreadsheet
C# Convert ADO.NET DataTable to Excel Spreadsheet PDF Print E-mail

Written by Steve Gourley,

This example takes a datatable of records and writes it to an excel spreadsheet. See Read more for the code.

 

     private void exportToExcell()
    {
        if (Session["DT"] != null)
        {
            System.Data.DataTable DT = Session["DT"] as DataTable;
            if (DT != null)
            {

                //clear anything in io buffer
                Response.Clear();
                //set to excel for to save file.
                Response.AddHeader("Content-Disposition""attachment;filename=FileName.xls");
                Response.Charset = "";
                Response.ContentType = "application/vnd.ms-excel";

                //write columns
                string tab = "";
                foreach (DataColumn dc in DT.Columns)
                {
                    Response.Write(tab + dc.ColumnName);
                    tab = "\t";
                }
                Response.Write("\n");

                //write rows
                int i;
                foreach (DataRow dr in DT.Rows)
                {
                    tab = "";
                    for (i = 0; i < DT.Columns.Count; i++)
                    {
                        Response.Write(tab + dr[i].ToString());
                        tab = "\t";
                    }
                    Response.Write("\n");
                }
                Response.End();
            }
        }
    }

Users' Comments  
 

No comment posted

Add your comment

09, Jan. 2008
Last Updated ( 09, Jan. 2008 )
 
< Prev   Next >

AGRC Contacts | UGIC Contacts

feed image feed image

Utah GIS Portal © 2009 AGRC

Optimized for