Other Improved Ways To Export Data To Excel

 /// <summary>
        /// Exports to excel. 
        /// http://www.codeproject.com/Articles/9380/Export-a-DataSet-to-Microsoft-Excel-without-the-us
        /// http://bytes.com/topic/c-sharp/answers/497730-streamwriter-export-excel
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <exception cref="System.Exception"></exception>
        public void ExportToExcel(DataSet source, string fileName)
        {

            //get response, set content type.
            HttpResponse response = HttpContext.Current.Response;
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" +
            fileName + "\"");
            response.Clear();
            System.IO.StreamWriter excelDoc;
            excelDoc = new System.IO.StreamWriter(response.OutputStream);


            /// excelDoc = new System.IO.StreamWriter(fileName);
            const string startExcelXML = "<xml version>\r\n<Workbook " +
                  "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
                  " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
                  "xmlns:x=\"urn:schemas-    microsoft-com:office:" +
                  "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
                  "office:spreadsheet\">\r\n <Styles>\r\n " +
                  "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
                  "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
                  "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
                  "\r\n <Protection/>\r\n </Style>\r\n " +
                  "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
                  "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
                  "<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
                  " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
                  "ss:ID=\"Decimal\">\r\n <NumberFormat " +
                  "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
                  "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
                  "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
                  "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
                  "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
                  "</Styles>\r\n ";
            const string endExcelXML = "</Workbook>";

            int rowCount = 0;
            int sheetCount = 1;
            /*
           <xml version>
           <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
           xmlns:o="urn:schemas-microsoft-com:office:office"
           xmlns:x="urn:schemas-microsoft-com:office:excel"
           xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
           <Styles>
           <Style ss:ID="Default" ss:Name="Normal">
             <Alignment ss:Vertical="Bottom"/>
             <Borders/>
             <Font/>
             <Interior/>
             <NumberFormat/>
             <Protection/>
           </Style>
           <Style ss:ID="BoldColumn">
             <Font x:Family="Swiss" ss:Bold="1"/>
           </Style>
           <Style ss:ID="StringLiteral">
             <NumberFormat ss:Format="@"/>
           </Style>
           <Style ss:ID="Decimal">
             <NumberFormat ss:Format="0.0000"/>
           </Style>
           <Style ss:ID="Integer">
             <NumberFormat ss:Format="0"/>
           </Style>
           <Style ss:ID="DateLiteral">
             <NumberFormat ss:Format="mm/dd/yyyy;@"/>
           </Style>
           </Styles>
           <Worksheet ss:Name="Sheet1">
           </Worksheet>
           </Workbook>
           */
            excelDoc.Write(startExcelXML);
            excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
            excelDoc.Write("<Table>");
            excelDoc.Write("<Row>");
            for (int x = 0; x < source.Tables[0].Columns.Count; x++)
            {
                excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
                excelDoc.Write(source.Tables[0].Columns[x].ColumnName);
                excelDoc.Write("</Data></Cell>");
            }
            excelDoc.Write("</Row>");
            foreach (DataRow x in source.Tables[0].Rows)
            {
                rowCount++;
                //if the number of rows is > 64000 create a new page to continue output
                if (rowCount == 64000)
                {
                    rowCount = 0;
                    sheetCount++;
                    excelDoc.Write("</Table>");
                    excelDoc.Write(" </Worksheet>");
                    excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
                    excelDoc.Write("<Table>");
                }
                excelDoc.Write("<Row>"); //ID=" + rowCount + "
                for (int y = 0; y < source.Tables[0].Columns.Count; y++)
                {
                    System.Type rowType;
                    rowType = x[y].GetType();
                    switch (rowType.ToString())
                    {
                        case "System.String":
                            string XMLstring = x[y].ToString();
                            XMLstring = XMLstring.Trim();
                            XMLstring = XMLstring.Replace("&", "&");
                            XMLstring = XMLstring.Replace(">", ">");
                            XMLstring = XMLstring.Replace("<", "<");
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                            excelDoc.Write(XMLstring);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DateTime":
                            //Excel has a specific Date Format of YYYY-MM-DD followed by  
                            //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
                            //The Following Code puts the date stored in XMLDate 
                            //to the format above
                            DateTime XMLDate = (DateTime)x[y];
                            string XMLDatetoString = ""; //Excel Converted Date
                            XMLDatetoString = XMLDate.Year.ToString() +
                                 "-" +
                                 (XMLDate.Month < 10 ? "0" +
                                 XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                                 "-" +
                                 (XMLDate.Day < 10 ? "0" +
                                 XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                                 "T" +
                                 (XMLDate.Hour < 10 ? "0" +
                                 XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                                 ":" +
                                 (XMLDate.Minute < 10 ? "0" +
                                 XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                                 ":" +
                                 (XMLDate.Second < 10 ? "0" +
                                 XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
                                 ".000";
                            excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
                                         "<Data ss:Type=\"DateTime\">");
                            excelDoc.Write(XMLDatetoString);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Boolean":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                        "<Data ss:Type=\"String\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                    "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Decimal":
                        case "System.Double":
                            excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                                  "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DBNull":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                  "<Data ss:Type=\"String\">");
                            excelDoc.Write("");
                            excelDoc.Write("</Data></Cell>");
                            break;
                        default:
                            throw (new Exception(rowType.ToString() + " not handled."));
                    }
                }
                excelDoc.Write("</Row>");
            }
            excelDoc.Write("</Table>");
            excelDoc.Write(" </Worksheet>");
            excelDoc.Write(endExcelXML);


            //flush and finish response
            excelDoc.Flush();
            excelDoc.Close();
            response.End();
        }

And to call it:


 /// <summary>
        /// Handles the Click event of the lbtnExportToExcel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbtnExportToExcel_Click(object sender, EventArgs e)
        {
            CommunicationsFilter filter = new CommunicationsFilter();

            filter = FilterControl.GetSearchFilter();
            int totalRowCount;
            List<SubscriberData> subData = CommDataManager.GetSubscribers(filter, 0, out totalRowCount);


            DataSet ds = new DataSet(); ds.Tables.Add(ConvertSubscriberDataToDataView(subData).ToTable());
            //ExportToExcel(ds, "MobileAlertsExport.xls");           

           

           
        }




  /// <summary>
        /// Converts the subscriber data to data view.
        /// </summary>
        /// <param name="subcriberData">The subcriber data.</param>
        /// <returns></returns>
        private DataView ConvertSubscriberDataToDataView(List<SubscriberData> subcriberData)
        {
            DataTable dt = new DataTable();

            // Define column headers
            dt.Columns.Add("First Name");
            dt.Columns.Add("Middle Initial");
            dt.Columns.Add("Last Name");
            dt.Columns.Add("Account Number");
            dt.Columns.Add("OPCO Abbrv Name");
            dt.Columns.Add("OPCO Full Name");
            dt.Columns.Add("Email");

            foreach (SubscriberData subscriber in subcriberData)
            {
                DataRow dr = dt.NewRow();

                dr["First Name"] = subscriber.FirstName;
                dr["Middle Initial"] = subscriber.MiddleInitial;
                dr["Last Name"] = subscriber.LastName;
                dr["Account Number"] = subscriber.SubscriberAccount.AccountNumberCheckDigit;
                dr["OPCO Abbrv Name"] = subscriber.OpCo.AbbreviatedName;
                dr["OPCO Full Name"] = subscriber.OpCo.FullName;
                dr["Email"] = subscriber.Email;

                dt.Rows.Add(dr);
            }

            //Load the datatable into a Dataview to accomodate easy sorting
            DataView dv = new DataView(dt);
            return dv;
        }

And for an even more native xlsx output check out http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm# which uses DocumentFormat.OpenXML.dll

Populate RadioButtonList From SQL Database

<%@ Control Language="C#" ClassName="PollControlAsync" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>

<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        BindRadioButtonListData(1);
    }

    
    private void BindRadioButtonListData(int PollID)
    {
        // connection string
        string connectionString = ConfigurationManager.ConnectionStrings["PollConnectionString"].ConnectionString;

        // Sql connection object initialized with connection string used to connect        
        using (SqlConnection mySqlConnection = new SqlConnection(connectionString))
        {
            try
            {
                // open the Sql connection
                mySqlConnection.Open();

                // Sql Command object initialized with SQL query to retrieve the categories
                SqlCommand mySqlCommand = new SqlCommand("SELECT * FROM [PollAnswers] WHERE ([PollID] = @PollID) ORDER BY [SortOrder]", mySqlConnection);   
                mySqlCommand.Parameters.AddWithValue("@PollID", PollID);             
                
                
                // Sql Data Adapter object initialized by passing the Sql Command object
                SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(mySqlCommand);


                // DataSet object to store the retrieved SQL data items
                DataSet myDataSet = new DataSet();

                // fill the DataSet
                mySqlDataAdapter.Fill(myDataSet);

                // Set DataSet object as DataSource for the RadioButtonList
                rblPollAnswers.DataSource = myDataSet;

                // Specify the Field Name that you want to display as
                // text label for Radio Button list item
                rblPollAnswers.DataTextField = "DisplayText";

                // Specify the Field Name that you want to use as
                // value for each list item
                rblPollAnswers.DataValueField = "PollAnswerID";

                // Finalize the DataBinding
                rblPollAnswers.DataBind();

            }
            catch (Exception ex)
            {
                Label1.Text = ex.Message;
            }
            finally
            {
                // close the Sql Connection
                mySqlConnection.Close();
            }
        }



    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
    }

    /// <summary>
    /// Gets or sets the poll ID.
    /// </summary>
    /// <value>The poll ID.</value>
    public int PollID
    {
        get
        {
            if (ViewState["PollID"] == null)
                return -1;
            else
                return (int)ViewState["PollID"];
        }
        set { ViewState["PollID"] = value; }
    }
  

</script>
<asp:RadioButtonList ID="rblPollAnswers" runat="server" />

How To Bind Custom Object To Build Dynamic CheckBoxList

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="InvestorDataFeedTest" %>

<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        
        if (!IsPostBack)
        {
            
            CBMaterialItems.DataSource = PrintedMaterialLogic.GetPrintedMaterialCBDataTable();
            CBMaterialItems.DataValueField = "MaterialID";
            CBMaterialItems.DataTextField = "MaterialName";
            CBMaterialItems.DataBind();

        }
        

    }

  
</script>

<html>
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBoxList ID="CBMaterialItems" runat="server" AutoPostBack="True" />
    </div>
    </form>
</body>
</html>

PrintedMaterialLogic.cs

using System;
using System.Collections.Generic;
using System.Web;

using System.Web.UI;
using System.Xml;
using System.Data;
using System.Reflection;
using System.Net;
using System.IO;
using System.Collections.Specialized;

namespace InvestorDataFeedTest
{
    public class PrintedMaterialLogic
    {

        public PrintedMaterialLogic() { }


        // Public Methods (Business Logic Layer)
        #region public static DataTable GetPrintedMaterialCBDataTable()
        //[DataObjectMethod(DataObjectMethodType.Select)]
        public static DataTable GetPrintedMaterialCBDataTable()
        {

            // Create an object to return
            DataTable datatable = new DataTable();

            try
            {
                List<PrintedMaterialData> entireList = new List<PrintedMaterialData>();

                entireList = GetPrintedMaterialCBData();

                datatable = ListToDataTable(entireList);
            }
            catch (Exception ex)
            {
                // Send error email
                BLL.SendErrorEmail("Get Printed Material CheckBox DataTable Error", "", ex);
            }


            return datatable;

        }
        #endregion    







        // Private Methods (Data Access Layer)
        #region public static List<PrintedMaterialData> GetPrintedMaterialCBData()
        public static List<PrintedMaterialData> GetPrintedMaterialCBData()
        {
            // Create object to return
            List<PrintedMaterialData> list = new List<PrintedMaterialData>();

            // Check cache for value first           
            Page page = (Page)HttpContext.Current.CurrentHandler;
            string cacheKey = "GetPrintedMaterialCBData";

            if (page.Cache[cacheKey] != null)
            {
                // Return cached value if it exists
                return (List<PrintedMaterialData>)page.Cache[cacheKey];
            }
            else
            {
                
                // Fill cache



                // Get XML
                string url = "http://xml.site.net/irxmlclient.asp?compid=343432&reqtype=informationrequest";
                string data = GetScreenScrape(url);

                XmlDocument xmlDoc = new XmlDocument();              
                xmlDoc.LoadXml(data);              


                // Get nodes
                XmlNodeList xmlNodes = xmlDoc.DocumentElement.SelectNodes("/IRXML/InformationRequest/InfoRequestMaterials/InfoRequestMaterial");
                // For each xml node, create the corresponding objects
                foreach (XmlNode xmlNode in xmlNodes)
                {

                    XmlElement elt = (XmlElement)xmlNode;

                    PrintedMaterialData node = PrintedMaterialCBDataCreate(xmlNode);

                    // If node was created, then add to our list
                    if (node != null) { list.Add(node); }
                }
            }


            return list;


        }
        #endregion
        #region public static PrintedMaterialData PrintedMaterialCBDataCreate(XmlNode xmlNode)
        public static PrintedMaterialData PrintedMaterialCBDataCreate(XmlNode xmlNode)
        {
            // Create an object to return
            PrintedMaterialData item = new PrintedMaterialData();

            if (xmlNode != null)
            {
                
                XmlNode materialNameNode = xmlNode.SelectSingleNode("MaterialName");                   
                XmlAttribute materialIDAttribute = xmlNode.Attributes["MaterialID"];

                item.MaterialName = (materialNameNode == null) ? "" : materialNameNode.InnerText.Trim();
                item.MaterialID = (materialIDAttribute == null) ? "" : materialIDAttribute.InnerText.Trim();     

                
                return item;
            }

            return null;
        }
        #endregion



        




        // Methods / Functions already in .COM Solution
        #region public static string GetScreenScrape(string url)
        public static string GetScreenScrape(string url)
        {
            // Create the WebRequest for the URL we are using
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)";
            // Get the stream from the returned web response
            StreamReader stream = new StreamReader(req.GetResponse().GetResponseStream());

            //experiment try reading entire thing at once
            string html = stream.ReadToEnd();


            // Finished with the stream so close it now
            stream.Close();

            return html;

        }
        #endregion
        #region private static DataTable ListToDataTable<T>(List<T> list)
        private static DataTable ListToDataTable<T>(List<T> list)
        {
            DataTable dt = new DataTable();

            foreach (PropertyInfo info in typeof(T).GetProperties())
            {
                dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
            }
            foreach (T t in list)
            {
                DataRow row = dt.NewRow();
                foreach (PropertyInfo info in typeof(T).GetProperties())
                {
                    row[info.Name] = info.GetValue(t, null);
                }
                dt.Rows.Add(row);
            }
            return dt;
        }
        #endregion




    }
}

How To Convert a DataSet into a Class

  • Open the Visual Studio .NET command prompt and browse to the directory where your XSD file exists.
  • Type the following at the prompt: xsd.exe SchemaName.xsd /DataSet /language:CS, where SchemaName.xsd is the name of your XSD file. In this example, the command line looks like this: xsd.exe Customers.xsd /DataSet /language:CS. For Visual Basic .NET, use /language:VB.
  • Look for your generated class file. In this sample, a file named Customers.cs will be created.
  • There are several options and flags for the xsd.exe tool, but the important flag for creating your strongly typed DataSet object is the /DataSet flag. This tells the tool to parse through the XSD file and autogenerate a strongly typed DataSet object for you. A view of the command line looks like this:

    C:\>xsd.exe Customers.xsd /DataSet /language:CS
    Microsoft (R) Xml Schemas/DataTypes support utility
    [Microsoft (R) .NET Framework, Version 1.1.4322.573]
    Copyright (C) Microsoft Corporation 1998-2002.
    All rights reserved.

    Writing file 'C:\Customers.cs'.

    C:\>

    Source