How to Export an entity collection to an Excel file? C#

Posts   
 
    
alkaholik
User
Posts: 7
Joined: 02-May-2007
# Posted on: 02-May-2007 20:25:06   

Hey all, i was wondering if anyone had some sample code for exporting an entity collection to an excel file to get me started, i'm using C# and asp 2.0.

This would be a big help all. thanks

jmeckley
User
Posts: 403
Joined: 05-Jul-2006
# Posted on: 02-May-2007 22:57:41   

I use this assembly to generate excel spreadsheets. simple, light weight, and doesn't require excel components. http://www.carlosag.net/Tools/ExcelXmlWriter/Default.aspx

as for the conversion

public void SaveCollectionToExcel(IEntityCollection collection, string fileName)
{
     //declare new workbook
     Workbook wb = new WorkBook();

     //add worksheet to workbook
     WorkSheet ws = new WorkSheet();
     wb.Worksheets.Add(ws);

     //header
     //declare new row & add to worksheet
     Row header = new Row();
     ws.Rows.Add(header);

     IEntityFields fields = collection.EntityFactoryToUse.CreateFields();
     foreach(IEntityFieldCore field in fields)
     {
          //declare a new cell, set text & append to row
          Cell cell = new Cell();
          cell.Text = field.Name;
          header.Cells.Add(cell);
     }

     //body
     foreach(IEntityCore entity in collection)
     {
          //append new row
          Row row = new Row();
          ws.Rows.Add(row);

          //append field values
          foreach(IEntityFieldCore field in entity.Fields)
          {
               //declare a new cell, set text & append to row
               Cell cell = new Cell();
               cell.Text = field.CurrentValue;
               row.Cells.Add(cell);
          }
     }

     ws.Save(fileName);
}

the link above details how exactly how to use the excel writer. you can format, protect, hide. my code is untested and the XLS object may not be named correctly, but this should get you started.

alkaholik
User
Posts: 7
Joined: 02-May-2007
# Posted on: 03-May-2007 01:43:50   

Thank bro, but i have a quick question. I am getting the following error:

"The type namespace name 'workbook' could not be found"

Here is what I have set up, am i missing one?:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Runtime.InteropServices;
using Telerik.WebControls;

using SD.LLBLGen.Pro.ORMSupportClasses;
using VirginiaAgency.LLBLGen.EntityClasses;
using VirginiaAgency.LLBLGen.CollectionClasses;
using VirginiaAgency.LLBLGen.DaoClasses;
using VirginiaAgency.LLBLGen.HelperClasses;
using VirginiaAgency.BusinessLogic.Helpers;
using VirginiaAgency.LLBLGen;
using Fnf.NetSolutions.Security.SecurityTemplate.Components;
using Fnf.NetSolutions.Security.SecurityTemplate;
daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 03-May-2007 10:00:00   

Hi, just for fun I test the DLL (http://www.carlosag.net/downloads.aspx?file=CarlosAg.ExcelXmlWriter.zip) and reading the documentation (http://www.carlosag.net/downloads.aspx?file=CarlosAg.ExcelXmlWriter.Help.zip) and have wrote this:

using System;
using System.Collections.Generic;
using System.Text;

using CarlosAg;
using CarlosAg.ExcelXmlWriter;

using SD.LLBLGen.Pro.ORMSupportClasses;

namespace EntityCollection_XLSWriter
{
    public class EntityCollectionXLSWriter
    {
        public void SaveCollectionToExcel(IEntityCollection2 collection, string fileName)
        {
            //declare new workbook
            Workbook wb = new Workbook();

            //add worksheet to workbook
            Worksheet ws = wb.Worksheets.Add("EntityExample");
            
            // needed to traverse fields
            IEntityFields2 fields = collection.EntityFactoryToUse.CreateFields();

            #region Define Workbook styles

            // add style to the workbook header
            WorksheetStyle headerStyle = wb.Styles.Add("HeaderStyle");
            headerStyle.Font.FontName = "Tahoma";
            headerStyle.Font.Size = 14;
            headerStyle.Font.Bold = true;
            headerStyle.Alignment.Horizontal = StyleHorizontalAlignment.Center;         
            headerStyle.Font.Color = "White";
            headerStyle.Interior.Color = "Blue";
            headerStyle.Interior.Pattern = StyleInteriorPattern.DiagCross;

            /// style for normal data cells..
            /// here you can add more styles depending upon content
            WorksheetStyle stringCellStyle = wb.Styles.Add("StringCellStyle");          
            stringCellStyle.Alignment.Horizontal = StyleHorizontalAlignment.Left;           
        

            #endregion

            #region Header Row

            // create the header based upon field names
            WorksheetRow header = new WorksheetRow();
            
            foreach (IEntityField2 field in fields)
            {
                //declare a new cell, set text & append to row
                WorksheetCell cell = new WorksheetCell(field.Name, "HeaderStyle");
                header.Cells.Add(cell);
            }
            
            // add the header row
            ws.Table.Rows.Add(header);

            #endregion

            #region Body Rows

            // traverse the entities in collection
            foreach (IEntity2 entity in collection)
            {
                // row
                WorksheetRow row = ws.Table.Rows.Add();

                // traverse the fields
                foreach (IEntityField2 field in fields)
                {
                    string valueToAdd = "";
                    DataType typeOfCell = DataType.String;

                    // test for null
                    if (entity.Fields[(field.FieldIndex)].CurrentValue != null)
                    {
                        valueToAdd = entity.Fields[(field.FieldIndex)].CurrentValue.ToString();

                        // define the type of the field
                        switch (entity.Fields[(field.FieldIndex)].CurrentValue.GetType().ToString())
                        {
                            case "System.Int32":
                                typeOfCell = DataType.Number;
                                break;

                            case "System.String":
                                typeOfCell = DataType.String;
                                break;

                            case "System.DateTime":
                                // should fix this... dont know how to populate correct dateTimes
                                typeOfCell = DataType.String;                               
                                //valueToAdd = ((DateTime)entity.Fields[(field.FieldIndex)].CurrentValue).ToShortDateString();
                                
                                break;

                            case "System.Decimal":
                                typeOfCell = DataType.Number;
                                break;

                            case "System.Boolean":
                                typeOfCell = DataType.Boolean;
                                break;                              
                        }
                    }

                    // add current cell
                    row.Cells.Add(valueToAdd, typeOfCell, "StringCellStyle");
                }
            }
            #endregion

            // save
            wb.Save(fileName);
        }
    }
}

Works ok. However I don't see much flexibility and still can't workaround the DateTime issue. And there's no much activity at the Change History at the author's site.

(Edit) http://www.codeproject.com/useritems/filehelpers.asp seems to be a better tool (last update: April/2007). Mentioned in thread http://www.llblgen.com/tinyforum/Messages.aspx?ThreadID=1940.

Please maintain us informed about your final approach wink

David Elizondo | LLBLGen Support Team