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

Dotnet Discussion :

C# import export de donnés vers excel


Sujet :

Dotnet

  1. #1
    Candidat au Club
    Homme Profil pro
    Inscrit en
    Juin 2013
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2013
    Messages : 5
    Points : 4
    Points
    4
    Par défaut C# import export de donnés vers excel
    Bonjour,

    Je développe une application .NET WPF en C#
    et je suis au stade ou j'ai un datagrid représentant une list<MaClasse>
    Je voudrai que l'utilisateur puisse exporter les donnés dans ce datagrid dans un tableur excel pour lui simplifier la saisie d'infos puis lorsqu'il a finit qu'il réimporte le tableur dans le programme pour que je puisse utiliser ensuite ces donnés dans le programme.

    Je suis de plus soumis a ces contraintes:
    - compatibilité maximum avec excel de 2007 a l'actuel
    - traitement de potentiellement une grande quantité de données

    Voila donc si quelqu’un ici a de l’expérience dans ce domaine je suis tout ouïe pour des bon tutos simples ou des bonnes pratiques la dessus
    Merci!!

  2. #2
    Membre éprouvé
    Avatar de dkmix
    Profil pro
    Inscrit en
    Septembre 2007
    Messages
    619
    Détails du profil
    Informations personnelles :
    Localisation : Jamaïque

    Informations forums :
    Inscription : Septembre 2007
    Messages : 619
    Points : 924
    Points
    924
    Par défaut
    Bonjour,
    Vous pouvez utiliser EPPLUS.
    Avantage : pas besoin de l'interop office (meilleures performances)
    exemple read/write Xlsx

  3. #3
    Candidat au Club
    Homme Profil pro
    Inscrit en
    Juin 2013
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2013
    Messages : 5
    Points : 4
    Points
    4
    Par défaut
    Merci,
    c'est vrai qu'a vue d’œil ça a l'air awesome je vais tester!
    faut juste que je trouve le bon moyen de convertir ma structure de donnée en datatable que je ne connais pas encore ^^
    je reviendrai dire si c'est un succès ou pas
    en attendant je reste ouvert aux autres propositions!

  4. #4
    Membre éprouvé
    Avatar de dkmix
    Profil pro
    Inscrit en
    Septembre 2007
    Messages
    619
    Détails du profil
    Informations personnelles :
    Localisation : Jamaïque

    Informations forums :
    Inscription : Septembre 2007
    Messages : 619
    Points : 924
    Points
    924
    Par défaut
    par exemple :
    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
    public 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;
    }

  5. #5
    Candidat au Club
    Homme Profil pro
    Inscrit en
    Juin 2013
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2013
    Messages : 5
    Points : 4
    Points
    4
    Par défaut
    bon-dieu ca marche tellement bien que j'en ai les larmes aux yeux!
    Merci!
    par contre dans ton lien d'exemple il y a deux erreurs assez faciles a corriger mais bon...
    Merci aussi pour le ListToDataTable, je n'utilise pas la réflexivité pour alléger.

    je met en PJ le fichier test et un résumé ici:

    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
     
            public static DataTable ListToDataTable(List<string> list)
            {
                DataTable dt = new DataTable();
     
                dt.Columns.Add(new DataColumn("cloom", typeof(string)));
                foreach (string t in list)
                {
                    DataRow row = dt.NewRow();
                    row["cloom"] = t;
                    dt.Rows.Add(row);
                }
                return dt;
            }
     
            public static List<string> DataTableToList(DataTable tabl)
            {
                List<string> lt = new List<string>();
     
                foreach (DataRow item in tabl.Rows)
                {
                    lt.Add(item.ItemArray[0] as string);
                }
                return lt;
            }
     
            public static DataTable ReadExcelFile(string path)
            {
                DataTable atable = new DataTable();
     
                using (StreamReader stream = new StreamReader(path))
                {
                    OfficeOpenXml.ExcelPackage packet = new ExcelPackage(stream.BaseStream);
                    ExcelWorkbook workbook = packet.Workbook;
     
                    if (workbook == null)
                    {
                        throw new Exception("Excel file has no workbooks!");
                    }
                    else
                    {
                        if (workbook.Worksheets.Count == 0)
                        {
                            throw new Exception("Excel file has no worksheets!");
                        }
                        else
                        {
                            ExcelWorksheet sheet = workbook.Worksheets.First();
     
                            int columnindex = 1;
                            for (int rowindex = 1; rowindex <= sheet.Dimension.End.Row; rowindex++)
                            {
     
                                if (rowindex == 1)
                                {
                                    bool foundlastcolumn = false;
                                    while (!foundlastcolumn)
                                    {
                                        object nullobject = null;
                                        DataColumn acolumn;
                                        if ((sheet.Cells[rowindex, columnindex].Value != nullobject))
                                        {
                                            acolumn = new
                                         DataColumn(sheet.Cells[rowindex, columnindex].Value.ToString());
                                            atable.Columns.Add(acolumn);
                                        }
                                        else
                                        {
                                            foundlastcolumn = true;
                                        }
                                        columnindex++;
                                    }
     
                                }
                                else
                                {
                                    int excelcolumnindex = 1;
                                    DataRow arow = atable.NewRow();
                                    for (int columnindexvalue = 0; columnindexvalue < atable.Columns.Count; columnindexvalue++)
                                    {
     
                                        arow[columnindexvalue] = sheet.Cells[rowindex, excelcolumnindex].Value;
                                        excelcolumnindex++;
                                    }
                                    atable.Rows.Add(arow);
                                    excelcolumnindex = 1;
                                }
                            }
     
                        }
     
                    }
                }
     
                return atable;
            }
     
            public static void ExportToExcel(DataTable table, string path, ExcelColumnHeaderStyle headerstyle)
            {
                using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    ExcelPackage packet = new ExcelPackage();
                    ExcelWorkbook werkboekie = packet.Workbook;
                    ExcelWorksheet mysheet = werkboekie.Worksheets.Add((string.IsNullOrEmpty(table.TableName) ? "HappyTable" : table.TableName));
     
                    mysheet.InsertRow(0, table.Rows.Count + 1);
     
                    int columnindex = 1;
                    foreach (DataColumn acolumn in table.Columns)
                    {
                        mysheet.Cells[1, columnindex].Value = acolumn.ColumnName;
                        columnindex++;
                    }
     
                    string columnrangeTo = "A1:" + GetColumnName(table.Columns.Count) + "1";
     
                    mysheet.Cells[columnrangeTo].Style.Font.Name =
                             (string.IsNullOrEmpty(headerstyle.Font) ? "Arial" : headerstyle.Font);
     
                    //set the font color
                    mysheet.Cells[columnrangeTo].Style.Font.Color.SetColor(headerstyle.FontColor);
     
                    //if font size is not set set it to 11 (default)
                    mysheet.Cells[columnrangeTo].Style.Font.Size =
                 (headerstyle.FontSize == 0 ? 11 : headerstyle.FontSize);
     
                    //this must be set in order to set the background color of each header column
                    mysheet.Cells[columnrangeTo].Style.Fill.PatternType = ExcelFillStyle.Solid;
     
                    //if the background color is not set, set it to white (default) else set it to chosen color
                    if (headerstyle.BackgroundColor.R == 0 && headerstyle.BackgroundColor.A == 0 && headerstyle.BackgroundColor.B == 0 && headerstyle.BackgroundColor.G == 0)
                        mysheet.Cells[columnrangeTo].Style.Fill.BackgroundColor.SetColor(Color.White);
                    else
                        mysheet.Cells[columnrangeTo].Style.Fill.BackgroundColor.SetColor(headerstyle.BackgroundColor);
                    mysheet.Cells[columnrangeTo].Style.Font.Bold = headerstyle.Bold;
                    mysheet.Cells[columnrangeTo].Style.Font.UnderLine = headerstyle.Underline;
     
                    int DatatableRowIndex = 0;
                    int DatatableColIndex = 0;
                    for (int rowindex = 2; rowindex <= table.Rows.Count+1; rowindex++)
                    {
                        for (int colindex = 1; colindex <= table.Columns.Count; colindex++)
                        {
                            string cellindex = GetColumnName(colindex) + rowindex;
                            mysheet.Cells[cellindex].Value = table.Rows[DatatableRowIndex][DatatableColIndex].ToString();
                            DatatableColIndex++;
                        }
                        DatatableColIndex = 0;
                        DatatableRowIndex++;
                    }
     
                    packet.SaveAs(stream);
                }
            }
     
            private static string GetColumnName(int index)
            {
                const int alphabetsCount = 26;
     
                if (index > alphabetsCount)
                {
                    int mod = index % alphabetsCount;
                    int columnIndex = index / alphabetsCount;
     
                    // if mod is 0 (clearly divisible) we reached end of one combination. Something like AZ
                    if (mod == 0)
                    {
                        // reducing column index as index / alphabetsCount will give the next value and we will miss
                        //one column.
                        columnIndex -= 1;
                        // passing 0 to the function will return character '@' which is invalid
                        // mod should be the alphabets count. So it takes the last char in the alphabet.
                        mod = alphabetsCount;
                    }
                    return GetColumnName(columnIndex) + GetColumnName(mod);
                }
                else
                {
                    int code = (index - 1) + (int)'A';
                    return char.ConvertFromUtf32(code);
                }
            }
     
            static void Main(string[] args)
            {
                List<String> toto = new List<string>()
                {
                    "kdd",
                    "uefo",
                    "plop",
                    "wqe",
                };
     
                DataTable tabl = ListToDataTable(toto);
                ExportToExcel(tabl, "AAheretest.xlsx", new ExcelColumnHeaderStyle());
     
                tabl = ReadExcelFile("AAheretest.xlsx");
                toto = DataTableToList(tabl);
            }
    Fichiers attachés Fichiers attachés

  6. #6
    Membre éprouvé
    Avatar de dkmix
    Profil pro
    Inscrit en
    Septembre 2007
    Messages
    619
    Détails du profil
    Informations personnelles :
    Localisation : Jamaïque

    Informations forums :
    Inscription : Septembre 2007
    Messages : 619
    Points : 924
    Points
    924
    Par défaut
    Par contre si la liste est vraiment grande il est preferable d'utiliser directement des datatable
    j'étais sur une liste d'objets, pour une list de string c'est pas génant

  7. #7
    Candidat au Club
    Homme Profil pro
    Inscrit en
    Juin 2013
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2013
    Messages : 5
    Points : 4
    Points
    4
    Par défaut
    ici c'est une liste de string pour proof of concept
    dans mon code réel ça sera une list<objetcustom>
    je ne connais pas encore a fond les datatables et j'ai pas le temps de réécrire tout mon code mais ca devrai aller ty!
    je passe en résolu.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [C#][EXCEL] import/export de données via excel
    Par desopedr dans le forum Windows Forms
    Réponses: 3
    Dernier message: 08/12/2006, 10h10
  2. export de données vers excel.
    Par songue77 dans le forum Bases de données
    Réponses: 10
    Dernier message: 21/07/2006, 09h41
  3. [En cours]Exporter des données vers Excel
    Par Muhad'hib dans le forum Contribuez
    Réponses: 2
    Dernier message: 12/01/2006, 14h25
  4. exporter des données vers EXCEL!
    Par JauB dans le forum Macros et VBA Excel
    Réponses: 11
    Dernier message: 25/11/2005, 15h13
  5. Export de données vers Excel
    Par psykot63 dans le forum Access
    Réponses: 2
    Dernier message: 03/01/2005, 12h04

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