Bienvenue à Blogs CodeS-SourceS Identification | Inscription | Aide

Julien Chable

He blogs, you blog, I blog ...

Archives

[Open XML] From IEnumerable<T> to Spreadsheet document

If you want to dump an IEnumerable<T> instance into an Excel spreadsheet document (using the latest Open XML SDK v2 CTP), here’s the code (also available in the zip in attachment) :

    static class OpenXMLExtensions
    {
        public static void ToSpreadsheetML<T>(this IEnumerable<T> items, String path) where T : class
        {
            ToSpreadsheetML<T>(items, new FileStream(path, FileMode.OpenOrCreate));
        }

        public static void ToSpreadsheetML<T>(this IEnumerable<T> items, Stream stream) where T : class
        {
            List<String> headers = (from PropertyInfo p in typeof(T).GetProperties() select p.Name).ToList<String>();

            List<List<String>> values = new List<List<String>>(items.Count());
            foreach (T item in items)
            {
                List<String> valCols = new List<string>();
                object obj = null;
                foreach (PropertyInfo property in typeof(T).GetProperties())
                {
                    obj = property.GetValue(item, null);
                    if (obj == null)
                        valCols.Add("");
                    else
                        valCols.Add(obj.ToString());
                }
                values.Add(valCols);
            }

            using (SpreadsheetDocument package =
                SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
            {
                package.PackageProperties.Creator = "Julien Chable - Wygwam (www.wygwam.com)";

                var workbookPart = package.AddWorkbookPart();
                GenerateWorkbookPart().Save(workbookPart);

                var worksheetPart = workbookPart.AddNewPart<WorksheetPart>("rId1");
                GenerateWorksheetPart(headers, values).Save(worksheetPart);
            }
        }

        #region Private methods

        private static Workbook GenerateWorkbookPart()
        {
            var element =
                new Workbook(
                    new BookViews(
                        new WorkbookView() { XWindow = 120, YWindow = 150, WindowWidth = (UInt32Value)19095U, WindowHeight = (UInt32Value)8415U }),
                    new Sheets(
                        new Sheet() { Name = "IEnumerableDemo", SheetId = (UInt32Value)1U, Id = "rId1" }));
            return element;
        }

        private static Worksheet GenerateWorksheetPart(List<String> headers, List<List<String>> values)
        {
            var element =
                new Worksheet(
                    new SheetViews(
                        new SheetView() { TabSelected = true, WorkbookViewId = (UInt32Value)0U }),
                    new SheetFormatProperties() { DefaultRowHeight = 15D },
                    PopulateData(headers, values));
            return element;
        }

        private static SheetData PopulateData(List<String> headers, List<List<String>> values)
        {
            Row headerRow = new Row();
            SheetData data = new SheetData(headerRow);

            foreach (String h in headers)
                headerRow.Append(new Cell(new CellValue(h)) { DataType = CellValues.String });

            foreach (List<String> vals in values)
            {
                Row valsRow = new Row();
                foreach (String val in vals)
                    valsRow.Append(new Cell(new CellValue(val)) { DataType = CellValues.String });
                data.AppendChild(valsRow);
            }
            return data;
        }

        #endregion
    }

The previous code add each object property with its value convert into a string (with ToString()) and then use the new Open XML SDK v2 to generate a document from scratch.

Here’s the example with a List<Person>:

List<Person> people = new List<Person>();
people.Add(new Person() { Name = "Julien",
                Blog = "
http://blogs.developpeur.org/neodante/" });
people.Add(new Person() { Name = "Aurélien",
                Blog = "
http://blogs.developpeur.org/aurelien/" });
people.ToSpreadsheetML("demo.xlsx");

image

Enjoy (thanks to Aurélien to have Linquify the code a bit)

Ce post vous a plu ? Ajoutez le dans vos favoris pour ne pas perdre de temps à le retrouver le jour où vous en aurez besoin :
Posted: lundi 15 septembre 2008 09:29 par neodante
Classé sous :

Attachment(s): OpenXMLExtensions.zip

Commentaires

Pas de commentaires

Les commentaires anonymes sont désactivés

Les 10 derniers blogs postés

- Evénement monfial Global Azure Bootcamp (10 000 participants) Venez !! par Blog de Vincent THAVONEKHAM, Objet Direct le 01-25-2015, 16:29

- Mon Blog déplacé vers une version anglaise... www.thavo.com par Blog de Vincent THAVONEKHAM, Objet Direct le 01-25-2015, 16:25

- Localisation et globalisation ne sont pas des options par Blog de Jérémy Jeanson le 01-17-2015, 11:47

- [Clean Code] les commentaires… par Fathi Bellahcene le 01-10-2015, 17:17

- Mise à jour de Test Professional 2013 par Blog de Jérémy Jeanson le 01-10-2015, 11:32

- [Dynamics CRM] Ajouter un bouton pour déclencher un workflow ou un script (dialogue) par Christine Dubois le 01-09-2015, 14:03

- RDV aux #SharePoint Days 2015 à Casablanca les 28 et 29 janvier ! par Le blog de Patrick [MVP Office 365] le 01-06-2015, 08:41

- TFS Online, vous allez aimer vos projets par Blog de Jérémy Jeanson le 01-03-2015, 11:19

- Bon code 2015 ! par Blog de Jérémy Jeanson le 01-02-2015, 19:01

- [Dynamics CRM] Créer un contact à partir d’une signature email par Christine Dubois le 12-30-2014, 14:37