IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Silverlight Discussion :

export données d'un datagrid(silverlight3) dans excel


Sujet :

Silverlight

  1. #1
    Membre confirmé
    Inscrit en
    Avril 2009
    Messages
    200
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 200
    Par défaut export données d'un datagrid(silverlight3) dans excel
    Bonjour

    je travail avec VS2008 et silverlight 3
    je dispose coté client d'un datagrid, il est créé avec un datatable (creation coté client de classe permetantd'avoir des datatable coté client je sais pas si sa a son importance mais je prefer le preciser)

    j'aimerai pouvoir exporter sur excel (format XLS) les données contenue dans mon datagrid.

    j'ai pas mal tourner mais impossible de trouver une solution qui convient.

    je ne vois pas d'inconvéniant ( a part techniquement ) a que sa soit fait coté serveur ou coté client.

    En esperant que vous aurez des solutions.

  2. #2
    Membre confirmé
    Inscrit en
    Avril 2009
    Messages
    200
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 200
    Par défaut
    je me permet de relancer cette discution, car apres de nombreuse recherche je n'ai pas trouver de solutions....

    coté client ou serveur ce n'est pa un pb !!

  3. #3
    Membre Expert
    Avatar de Pragmateek
    Homme Profil pro
    Formateur expert .Net/C#
    Inscrit en
    Mars 2006
    Messages
    2 635
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Formateur expert .Net/C#
    Secteur : Conseil

    Informations forums :
    Inscription : Mars 2006
    Messages : 2 635
    Par défaut
    Une méthode simple est de transformer les données au format CSV qui est directement interprétable par Excel.

    Il me semble que FileHelpers (http://filehelpers.sourceforge.net/) est une bonne lib pour le traitement CSV.

  4. #4
    Membre éclairé
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Juillet 2003
    Messages
    50
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Juillet 2003
    Messages : 50
    Par défaut
    Salut,

    J'ai eu les mêmes besoins récemment.
    J'ai créé un webservice qui me convertir des données sous formes de tableau en fichier xls en utilisant l'api excel.
    Si tu as Office 2007 ou supérieur, tu peux produire un xml.
    J'avais trouvé cette class sur internet, mais je sais plus trop ou.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
     
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Reflection;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Ink;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
     
    namespace Excel.Business
    {
        /// <summary>
        /// Class that handle Export to XML that are compliant with Excel 2007 or higher.
        /// </summary>
        public static class ExcelXml
        {
            /// <summary>
            /// Export the given DataGrid to Excel XML.
            /// </summary>
            /// <param name="myGrid">Datagrid to export.</param>
            public static void ExportToExcelXml(DataGrid myGrid)
            {
                if (myGrid.ItemsSource == null)
                {
                    MessageBox.Show("No Data to export!");
                    return;
                }
     
                SaveFileDialog objSFD = new SaveFileDialog() { DefaultExt = "xml", Filter = "Excel XML (*.xml)|*.xml|CSV Files (*.csv)|*.csv|All files (*.*)|*.*", FilterIndex = 1 };
                if (objSFD.ShowDialog() == true)
                {
                    MessageBoxResult res = MessageBox.Show("Full export ?", "Export type", MessageBoxButton.OKCancel);
                    if (res == MessageBoxResult.OK)
                    {
                        ExportFullSource(objSFD, myGrid);
                    }
                    else
                    {
                        ExportDataGrid(objSFD, myGrid);
                    }
                }
            }
     
            /// <summary>
            /// Export the entire source of the datagrid to Excel.
            /// </summary>
            /// <param name="objSFD">Object that contains the name of the file that will have datas.</param>
            /// <param name="myGrid">Datagrid to export.</param>
            private static void ExportFullSource(SaveFileDialog objSFD, DataGrid myGrid)
            {
                bool firstRow = true;
     
                LinkedList<string> columns = new LinkedList<string>();
     
                string strFormat = objSFD.SafeFileName.Substring(objSFD.SafeFileName.IndexOf('.') + 1).ToUpper();
                StringBuilder strBuilder = new StringBuilder();
                List<string> lstFields = new List<string>();
     
                try
                {
                    foreach (object data in myGrid.ItemsSource)
                    {
                        Type objectType = data.GetType();
                        if (firstRow)
                        {
                            foreach (PropertyInfo item in objectType.GetProperties())
                            {
                                columns.AddLast(item.Name);
                                lstFields.Add(FormatField(item.Name, strFormat));
                            }
                            BuildStringOfRow(strBuilder, lstFields, strFormat);
                            firstRow = false;
                        }
                        lstFields.Clear();
                        foreach (string itemProp in columns)
                        {
                            PropertyInfo f = objectType.GetProperty(itemProp);
                            if (f.GetValue(data, null) == null)
                            {
                                lstFields.Add(FormatField(string.Empty, strFormat));
                            }
                            else
                            {
                                lstFields.Add(FormatField(f.GetValue(data, null).ToString(), strFormat));
                            }
                        }
                        BuildStringOfRow(strBuilder, lstFields, strFormat);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    WriteExcelXmlFile(objSFD, strFormat, strBuilder);
                    MessageBox.Show("Export Done!!!");
                }
            }
     
            /// <summary>
            /// Export visible datas to an excel sheet.
            /// </summary>
            /// <param name="objSFD">Object that contains the name of the file that will have datas.</param>
            /// <param name="myGrid">Datagrid to export.</param>
            private static void ExportDataGrid(SaveFileDialog objSFD, DataGrid myGrid)
            {
                string strFormat = objSFD.SafeFileName.Substring(objSFD.SafeFileName.IndexOf('.') + 1).ToUpper();
                StringBuilder strBuilder = new StringBuilder();
                List<string> lstFields = new List<string>();
     
                if (myGrid.HeadersVisibility == DataGridHeadersVisibility.Column || myGrid.HeadersVisibility == DataGridHeadersVisibility.All)
                {
                    foreach (DataGridColumn dgcol in myGrid.Columns)
                    {
                        lstFields.Add(FormatField(dgcol.Header.ToString(), strFormat));
                    }
                    BuildStringOfRow(strBuilder, lstFields, strFormat);
                }
                try
                {
                    foreach (object data in myGrid.ItemsSource)
                    {
                        lstFields.Clear();
                        foreach (DataGridColumn col in myGrid.Columns)
                        {
                            string strValue = string.Empty;
                            Binding objBinding = null;
                            if (col is DataGridBoundColumn)
                            {
                                objBinding = (col as DataGridBoundColumn).Binding;
                            }
                            if (col is DataGridTemplateColumn)
                            {
                                // This is a template column... let us see the underlying dependency object
                                try
                                {
                                    DependencyObject objDO = (col as DataGridTemplateColumn).CellTemplate.LoadContent();
     
                                    FrameworkElement oFE = (FrameworkElement)objDO;
                                    FieldInfo oFI = oFE.GetType().GetField("TextProperty");
                                    if (oFI != null)
                                    {
                                        if (oFI.GetValue(null) != null)
                                        {
                                            if (oFE.GetBindingExpression((DependencyProperty)oFI.GetValue(null)) != null)
                                            {
                                                objBinding = oFE.GetBindingExpression((DependencyProperty)oFI.GetValue(null)).ParentBinding;
                                            }
                                        }
                                    }
                                }
                                catch 
                                { 
                                    objBinding = null; 
                                }
                            }
                            if (objBinding != null)
                            {
                                if (objBinding.Path.Path != string.Empty)
                                {
                                    PropertyInfo pi = data.GetType().GetProperty(objBinding.Path.Path);
                                    if (pi != null)
                                    {
                                        strValue = pi.GetValue(data, null).ToString();
                                    }
                                }
                                if (objBinding.Converter != null)
                                {
                                    if (strValue != string.Empty)
                                    {
                                        strValue = objBinding.Converter.Convert(strValue, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();
                                    }
                                    else
                                    {
                                        strValue = objBinding.Converter.Convert(data, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();
                                    }
                                }
                            }
                            lstFields.Add(FormatField(strValue, strFormat));
                        }
                        BuildStringOfRow(strBuilder, lstFields, strFormat);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                WriteExcelXmlFile(objSFD, strFormat, strBuilder);
                MessageBox.Show("Export Done!!!");
            }
     
            /// <summary>
            /// Write to Excel XML file.
            /// </summary>
            /// <param name="objSFD">Object that contains destination filename.</param>
            /// <param name="strFormat">XML to indicate the destination is a XML file, otherwise it is a CSV file.</param>
            /// <param name="strBuilder">Datas well formatted.</param>
            private static void WriteExcelXmlFile(SaveFileDialog objSFD, string strFormat, StringBuilder strBuilder)
            {
                StreamWriter sw = new StreamWriter(objSFD.OpenFile());
                if (strFormat == "XML")
                {
                    // Let us write the headers for the Excel XML
                    sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                    sw.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>");
                    sw.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\">");
                    sw.WriteLine("<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
                    sw.WriteLine("<Author>" + App.Current.Host.InitParams["UserName"].ToString() + "</Author>");
                    sw.WriteLine("<Created>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</Created>");
                    sw.WriteLine("<LastSaved>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</LastSaved>");
                    sw.WriteLine("<Company>My Company</Company>");
                    sw.WriteLine("<Version>12.00</Version>");
                    sw.WriteLine("</DocumentProperties>");
                    sw.WriteLine("<Worksheet ss:Name=\"Excel Export\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">");
                    sw.WriteLine("<Table>");
                }
                sw.Write(strBuilder.ToString());
                if (strFormat == "XML")
                {
                    sw.WriteLine("</Table>");
                    sw.WriteLine("</Worksheet>");
                    sw.WriteLine("</Workbook>");
                }
                sw.Close();
            }
     
            /// <summary>
            /// Build the destination string.
            /// </summary>
            /// <param name="strBuilder">Destination buffer.</param>
            /// <param name="lstFields">Collection of string that contains row datas.</param>
            /// <param name="strFormat">Format of the destination file. Xml or Csv.</param>
            private static void BuildStringOfRow(StringBuilder strBuilder, List<string> lstFields, string strFormat)
            {
                switch (strFormat)
                {
                    case "XML":
                        strBuilder.AppendLine("<Row>");
                        strBuilder.AppendLine(String.Join("\r\n", lstFields.ToArray()));
                        strBuilder.AppendLine("</Row>");
                        break;
                    case "CSV":
                        strBuilder.AppendLine(String.Join(",", lstFields.ToArray()));
                        break;
                }
            }
     
            /// <summary>
            /// Format field regarding destination file format.
            /// </summary>
            /// <param name="data">Data to fomat.</param>
            /// <param name="format">Format of the destination file. Xml or CSV.</param>
            /// <returns>Formatted field.</returns>
            private static string FormatField(string data, string format)
            {
                switch (format)
                {
                    case "XML":
                        return String.Format("<Cell><Data ss:Type=\"String\">{0}</Data></Cell>", data);
                    case "CSV":
                        return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", string.Empty).Replace("\r", string.Empty));
                }
                return data;
            }
        }
    }
    A+,
    MasterSleepy.

Discussions similaires

  1. Extraction de données vers d'autres feuilles dans Excel 2007
    Par josef-68 dans le forum Macros et VBA Excel
    Réponses: 2
    Dernier message: 26/11/2010, 16h23
  2. [XL-2003] Exporter résultats cases à cocher formulaire word dans excel
    Par macat dans le forum Macros et VBA Excel
    Réponses: 8
    Dernier message: 10/12/2009, 15h54
  3. exporter données d'un datagrid vers excel
    Par kat40 dans le forum VB 6 et antérieur
    Réponses: 21
    Dernier message: 18/03/2008, 16h25
  4. Exporter les données change banque de france dans Excel
    Par joegalere dans le forum Macros et VBA Excel
    Réponses: 6
    Dernier message: 12/11/2007, 12h33
  5. Exporter les données d'un datagrid dasn un excel
    Par Alabama-song dans le forum ASP.NET
    Réponses: 4
    Dernier message: 07/08/2007, 15h46

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo