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

- VMMap en mode instrumentation sur système 64bit : attention à la plateforme cible du build .NET par CoqBlog le il y a 3 heures et 0 minutes

- Etendre le Team Web Access de TFS 2012 – Step 0 par Philippe Didiergeorges Aka Philess le 05-23-2013, 23:48

- Simuler facilement l’envoi de mail par Blog de Jérémy Jeanson le 05-22-2013, 12:52

- ProcDump 6.0 : support du filtrage sur messages d'exceptions .NET, des filtres multiples et du ciblage par nom de service par CoqBlog le 05-20-2013, 14:50

- Votez pour le TOP 10 des influenceurs SharePoint francophones ! par Le blog de Patrick [MVP SharePoint] le 05-20-2013, 12:59

- [Conf’SharePoint] Dernier rappel ! :-) par Le blog de Patrick [MVP SharePoint] le 05-20-2013, 09:09

- [ #SharePoint 2013 ] les modèles de sites standards… par Le blog de Patrick [MVP SharePoint] le 05-20-2013, 09:03

- 10 erreurs de compréhension concernant SharePoint… par Le blog de Patrick [MVP SharePoint] le 05-20-2013, 08:27

- Conf’SharePoint : 10 bonnes raisons pour ne pas la rater par Le petit blog de Pierre / Pierre's little blog le 05-14-2013, 02:24

- [Event] Soirée de lancement Agile .NET France à Lyon par Blog Agile/ALM de Vincent THAVONEKHAM le 05-13-2013, 01:29