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

C# Discussion :

C# et Linq : Tri multiple d'un fichier CSV


Sujet :

C#

  1. #1
    Membre à l'essai
    Homme Profil pro
    Informatique
    Inscrit en
    Janvier 2012
    Messages
    20
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Informatique
    Secteur : Enseignement

    Informations forums :
    Inscription : Janvier 2012
    Messages : 20
    Points : 16
    Points
    16
    Par défaut C# et Linq : Tri multiple d'un fichier CSV
    Bonjour,

    Je souhaiterais faire une application avec C# (.Net) sous VS, qui permet de trier des fichiers (.csv) selon 5 critères (colonnes)
    voilà ce que j'ai fait mais ça ne marche pas. Quelqu'un peut il m'aider à corriger ma requête Linq?

    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
     
                //Ecriture des données dans le fichier de déstination
                using (var writer = new StreamWriter(@"" + this.textBox2.Text))
                {
                    foreach 
                        (
                        Contrat c in listeContrats.OrderBy(x => x.NUMCCI).ThenBy(x=> x.NUMRNG)
                        .ThenBy(x =>x.DEBGAR).ThenBy(x =>x.FINGAR)
                        )
                    {
                        writer.WriteLine(c.ligne);
                    }
     
                }
                MessageBox.Show("Success. ");
            }
    Je vous remercie par avance.

    Slim025

  2. #2
    Membre confirmé
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Octobre 2010
    Messages
    173
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2010
    Messages : 173
    Points : 485
    Points
    485
    Par défaut
    Salut,

    quand tu dis que ça ne marche pas, tu parles de quoi car je ne vois pas d'erreur de synthaxe.

  3. #3
    Membre à l'essai
    Homme Profil pro
    Informatique
    Inscrit en
    Janvier 2012
    Messages
    20
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Informatique
    Secteur : Enseignement

    Informations forums :
    Inscription : Janvier 2012
    Messages : 20
    Points : 16
    Points
    16
    Par défaut
    Salut fozzeuh,
    En fait, ça ne me fait pas mon tri. en fait un peu en haut dans mon code j'ai une liste. je lis le fichier csv et je le split.
    Dans la colonne FINGAR (date de fin de garantie) y a des valeurs comme ça 99999999. Il faut que je fasse un test (je ne sais pas comment) avant le parse. (genre je change temporairement la valeur 99999999 en 01011900 juste pour faire le test puis dans l'écriture du fichier la rend comme elle était c-a-d 99999999.
    Mais ça ce n'est pas mon problème qui me presse.
    Ce que je veux faire dans l'immédiat, c'est de faire une requête linq ou autre qui me permet de trier hierarchiquement mes données. càd dans le groupe de lignes qui ont le même Numéro de contrat (NUMCCI) je trie par (NUMCCI,NUMRNG,DEBGAR,FINGAR)
    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
     StreamReader file = new StreamReader(@"" + this.textBox1.Text);
                while ((line = file.ReadLine()) != null)
                {
                    //System.Console.WriteLine(line);
                    string[] split = line.Split(new Char[] { ';' });
                    if (!"".Equals(split[0]))
                    {
                        var NUMCCI= split[0];
                        var DEBCTR= split[1];
                        var FINCTR= split[2];
                        var NUMRNG= split[57];
                        var CODPRD= split[234];
                        var CODGAR= split[235];
                        var DEBGAR= split[236];// date
                        var FINGAR= split[237];//date 
                        var ligne = line;
     
                        listeContrats.Add(new Contrat
                        {
                            NUMCCI=NUMCCI,
                            DEBCTR=DEBCTR,
                            FINCTR=FINCTR,
                            NUMRNG=NUMRNG,
                            CODPRD=CODPRD,
                            CODGAR=CODGAR,
                            DEBGAR =DEBGAR, // il faut que je convertie ce champ en date
                            FINGAR =FINGAR, //il faut que je convertie ce champ en date
                            ligne=ligne,
                        });
                    }
                    counter++;
     
                }
    Je te remercie par avance.

    Slim025

    Citation Envoyé par fozzeuh Voir le message
    Salut,

    quand tu dis que ça ne marche pas, tu parles de quoi car je ne vois pas d'erreur de synthaxe.

  4. #4
    Membre confirmé
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Octobre 2010
    Messages
    173
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2010
    Messages : 173
    Points : 485
    Points
    485
    Par défaut
    Tu pourrais me fournir un CSV d'exemple pour que je teste ?

  5. #5
    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,

    Selon la taille et les perfs souhaités, il est possible de de faire comme ceci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    using (var manager = new CsvManager())
      {
         DataTable dt = new DataTable();
         manager.ReadCsv(dt, "NomDemOnFIchier.csv", false, Encoding.Default,',');
     
           dt.DefaultView.Sort = " ... ";
         ...
         dt.Dispose();
     }
    DataView.Sort

    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
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
     
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
     
    namespace Files.Csv
    {
        /// <summary>
        /// Classe pour gerer les fichiers CSV
        /// </summary>
        public class CsvManager : IDisposable
        {
            private const char SEPARATOR_CHAR = ';';
     
            ~CsvManager()
            {
                // Finalizer calls Dispose(false)
                Dispose(false);
            }
     
            #region "Write"
     
            /// <summary>
            /// Transformation d'un Datatable en fichier CSV.
            /// </summary>
            /// <param name="table">Datatable contenant les infos à écrire.</param>
            /// <param name="fileName">Nom complet du fichier de sortie.</param>
            /// <param name="hasColumnHeader">Spécifie si on utilise la première ligne comme entête.</param>
            /// <param name="separator">Caractère de séparation (par défaut : ';') </param>
            public void WriteCsv(DataTable table, string fileName, bool hasColumnHeader, char separator = SEPARATOR_CHAR)
            {
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
     
                using (Stream sTWritter = File.Create(fileName))
                {
                    WriteCsv(table, sTWritter, hasColumnHeader, separator);
                }
            }
     
            /// <summary>
            /// Transformation d'un Datatable en <see cref="Stream"/>.
            /// </summary>
            /// <param name="table">Datatable contenant les infos à écrire.</param>
            /// <param name="stream">Le <see cref="Stream"/> dans lequel on écrit.</param>
            /// <param name="hasColumnHeader">Spécifie si on utilise la première ligne comme entête.</param>
            /// <param name="separator">Caractère de séparation (par défaut : ';') </param>
            public void WriteCsv(DataTable table, Stream stream, bool hasColumnHeader, char separator = SEPARATOR_CHAR)
            {
                using (var txtWritter = new StreamWriter(stream))
                {
                    WriteCsv(table, txtWritter, hasColumnHeader, separator);
                }
            }
     
            /// <summary>
            /// Transformation d'un Datatable en <see cref="TextWriter"/>.
            /// </summary>
            /// <param name="table">Datatable contenant les infos à écrire.</param>
            /// <param name="writer">Le <see cref="TextWriter"/> dans lequel on écrit.</param>
            /// <param name="hasColumnHeader">Spécifie si on utilise la première ligne comme entête.</param>
            /// <param name="separator">Caractère de séparation (par défaut : ';') </param>
            public void WriteCsv(DataTable table, TextWriter writer, bool hasColumnHeader, char separator = SEPARATOR_CHAR)
            {
                if (hasColumnHeader)
                {
                    for (int index = 0; index <= table.Columns.Count - 1; index++)
                    {
                        if (index > 0)
                        {
                            writer.Write(separator);
                        }
     
                        writer.Write(QuoteText(table.Columns[index].ColumnName, separator));
                    }
     
                    writer.WriteLine();
                }
     
                for (int rowIndex = 0; rowIndex <= table.Rows.Count - 1; rowIndex++)
                {
                    for (int colIndex = 0; colIndex <= table.Columns.Count - 1; colIndex++)
                    {
                        if (colIndex > 0)
                        {
                            writer.Write(separator);
                        }
     
                        writer.Write(QuoteText(Convert.ToString(table.Rows[rowIndex][colIndex], CultureInfo.InvariantCulture), separator));
                    }
     
                    writer.WriteLine();
                }
            }
            #endregion
     
            #region "Read"
     
            /// <summary>
            /// Transformation d'un fichier CSV en <see cref="DataTable"/>
            /// </summary>
            /// <param name="table">Le <see cref="DataTable"/> dans lequel on écrit les données.</param>
            /// <param name="fileName">Nom du fichier CSV pour la lecture des données.</param>
            /// <param name="hasColumnHeader">Spécifie si on utilise la première ligne comme entête.</param>
            /// <param name="encoding">Encodage utilisé</param>
            /// <param name="separator">Caractère de séparation (par défaut : ';') </param>
            /// <param name="deleteLastChar">Suppression du dernier caractère</param>
            public void ReadCsv(DataTable table, string fileName, bool hasColumnHeader, Encoding encoding, char separator = SEPARATOR_CHAR, bool deleteLastChar = false)
            {
                using (Stream st = File.OpenRead(fileName))
                {
                    ReadCsv(table, st, hasColumnHeader, encoding, separator, deleteLastChar);
                }
            }
     
            /// <summary>
            /// Transformation d'un <see cref="Stream"/> en <see cref="DataTable"/>
            /// </summary>
            /// <param name="table">Le <see cref="DataTable"/> dans lequel on écrit les données.</param>
            /// <param name="stream">Le <see cref="Stream"/> utilisé pour la lecture des données.</param>
            /// <param name="hasColumnHeader">Spécifie si on utilise la première ligne comme entête.</param>
            /// <param name="encoding">Encodage utilisé</param>
            /// <param name="separator">Caractère de séparation (par défaut : ';') </param>
            /// <param name="deleteLastChar">Suppression du dernier caractère</param>
            public void ReadCsv(DataTable table, Stream stream, bool hasColumnHeader, Encoding encoding, char separator = SEPARATOR_CHAR, bool deleteLastChar = false)
            {
                using (TextReader txtReader = new StreamReader(stream, encoding))
                {
                    ReadCsv(table, txtReader, hasColumnHeader, separator, deleteLastChar);
                }
            }
     
            /// <summary>
            /// Transformation d'un <see cref="TextReader"/> en <see cref="DataTable"/> .
            /// </summary>
            /// <param name="table">Le <see cref="DataTable"/> dans lequel on écrit les données.</param>
            /// <param name="reader">Le <see cref="TextReader"/> utilisé pour la lecture des données.</param>
            /// <param name="hasColumnHeader">Spécifie si on utilise la première ligne comme entête.</param>
            /// <param name="separator">Caractère de séparation (par défaut : ';') </param>
            /// <param name="deleteLastChar">Suppression du dernier caractère</param>
            public void ReadCsv(DataTable table, TextReader reader, bool hasColumnHeader, char separator = SEPARATOR_CHAR, bool deleteLastChar = false)
            {
                string line = reader.ReadLine();
                if (string.IsNullOrEmpty(line))
                {
                    return;
                }
     
                string[] parts = ReadParts(line, separator, deleteLastChar);
     
                if (hasColumnHeader)
                {
                    foreach (string part in parts)
                    {
                        table.Columns.Add(part, typeof(string));
                    }
     
                    line = reader.ReadLine();
                }
                else
                {
                    foreach (string part in parts)
                    {
                        table.Columns.Add().DataType = typeof(string);
                    }
                }
     
                while (!string.IsNullOrEmpty(line))
                {
                    parts = ReadParts(line, separator);
     
                    DataRow row = table.NewRow();
                    for (int index = 0; index <= parts.Length - 1; index++)
                    {
                        if (parts[index].Equals(separator.ToString()))
                        {
                            parts[index] = string.Empty;
                        }
                        else
                        {
                            row[index] = parts[index];
                        }
                    }
     
                    table.Rows.Add(row);
                    line = reader.ReadLine();
                }
            }
     
            #endregion
     
            /// <summary>
            /// Dispose les ressources
            /// </summary>
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
     
            /// <summary>
            /// Dispose les ressources
            /// </summary>
            /// <param name="disposing">Is Disposing</param>
            protected virtual void Dispose(bool disposing)
            {
                if (disposing)
                {
                    // free managed resources               
                }
            }
     
            #region private
     
            private string[] ReadParts(string line, char separator, bool deletelastChar = false)
            {
                // Suppression du dernier caractère de séparation en cas de csv mal formaté
                if (deletelastChar == true)
                {
                    if (line.EndsWith(separator.ToString()))
                    {
                        line = line.Substring(0, line.Length - 1);
                    }
                }
     
                List<string> parts = new List<string>();
     
                bool inQuotes = false;
                int partIndex = 0;
                int endPartIndex = 0;
                for (int index = 0; index <= line.Length - 1; index++)
                {
                    if (inQuotes)
                    {
                        if (line[index] == '"')
                        {
                            endPartIndex = index - 1;
                            inQuotes = false;
                        }
                        else
                        {
                            endPartIndex = index;
                        }
                    }
                    else
                    {
                        if (line[index] == '"')
                        {
                            partIndex = index + 1;
                            endPartIndex = partIndex;
                            inQuotes = true;
                        }
                        else if (line[index] == separator)
                        {
                            parts.Add(line.Substring(partIndex, endPartIndex - partIndex + 1));
                            partIndex = index + 1;
                            endPartIndex = partIndex;
                        }
                        else
                        {
                            endPartIndex = index;
                        }
                    }
                }
     
                if (!line.Length.Equals(partIndex))
                {
                    parts.Add(line.Substring(partIndex, endPartIndex - partIndex + 1));
                }
                else
                {
                    parts.Add(string.Empty);
                }
     
                return parts.ToArray();
            }
     
            private string QuoteText(object value, char separator)
            {
                if (value == null || Convert.IsDBNull(value))
                {
                    return string.Empty;
                }
     
                string strValue = value.ToString();
                if (strValue.Contains(separator))
                {
                    return "\"" + strValue + "\"";
                }
                else
                {
                    return strValue;
                }
            }
     
            #endregion
        }
    }

  6. #6
    Membre à l'essai
    Homme Profil pro
    Informatique
    Inscrit en
    Janvier 2012
    Messages
    20
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Informatique
    Secteur : Enseignement

    Informations forums :
    Inscription : Janvier 2012
    Messages : 20
    Points : 16
    Points
    16
    Par défaut
    Bonjour fozzeuh,

    Ci-joint un fichier csv pour tester mon code.
    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
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Resources;
    using System.Reflection;
     
    namespace triFichier
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
     
            private void button2_Click(object sender, EventArgs e)
            {
                // call will result a value from the DialogResult enum
                // when the dialog is dismissed.
                DialogResult result = this.openFileDialog1.ShowDialog();
                // if a file is selected
                if (result == DialogResult.OK)
                {
                    // Set the selected file URL to the textbox
                    this.textBox1.Text = this.openFileDialog1.FileName;
                }
            }
     
            private void button1_Click(object sender, EventArgs e)
            {
                int counter = 0;
                string line;
                List<Contrat> listeContrats = new List<Contrat>();
                Dictionary<string, List<Contrat>> tableau = new Dictionary<string, List<Contrat>>();
                //Read the file and display it line by line.
                if (this.textBox1.Text == "" || this.textBox2.Text == "")
                {
                    MessageBox.Show("Veuillez remplire les champs");
                    return;
                }
                StreamReader file = new StreamReader(@"" + this.textBox1.Text);
                while ((line = file.ReadLine()) != null)
                {
                    //System.Console.WriteLine(line);
                    string[] split = line.Split(new Char[] { ';' });
                    if (!"".Equals(split[0]))
                    {
                        var NUMCCI= split[0];
                        var DEBCTR= split[1];
                        var FINCTR= split[2];
                        var NUMRNG= split[57];
                        var CODPRD= split[234];
                        var CODGAR= split[235];
                        var DEBGAR= split[236];
                        var FINGAR= split[237];
     
                        //try 
                        //if (FINGAR !='99999999' and 
                        //var DEBGAR = DateTime.ParseExact(split[236], "YYYYMMDD", CultureInfo.InvariantCulture);
                        //var FINGAR = DateTime.ParseExact(split[237], "YYYYMMDD", CultureInfo.InvariantCulture);
                        //catch
                        //{}
     
                        var ligne = line;
     
                        listeContrats.Add(new Contrat
                        {
                            NUMCCI=NUMCCI,
                            DEBCTR=DEBCTR,
                            FINCTR=FINCTR,
                            NUMRNG=NUMRNG,
                            CODPRD=CODPRD,
                            CODGAR=CODGAR,
                            DEBGAR =DEBGAR,
                            FINGAR =FINGAR,
                            ligne=ligne,
                        });
                    }
                    counter++;
     
                }
                IEnumerable<string> requete = from Contrat in listeContrats
                                    orderby Contrat.NUMCCI, Contrat.NUMRNG,Contrat.DEBGAR,Contrat.FINGAR
                                    select Contrat.ligne;
                var res = (from r in listeContrats select r.NUMCCI).Distinct().ToList(); ;
     
                foreach (string c in res)
                {
                    tableau.Add(c, listeContrats.Where(x => x.NUMCCI == c).ToList());
                }
                file.Close();
     
                //Ecriture des données dans le fichier de déstination
                using (var writer = new StreamWriter(@"" + this.textBox2.Text))
                {
                    foreach (Contrat c in listeContrats.OrderBy(x => x.NUMCCI).)
                    {
                        writer.WriteLine(c.ligne);
                    }
                    //foreach
                    //    (string ligne in requete
                    //    //Contrat c in 
                    //    //listeContrats.OrderBy(x => x.NUMCCI).OrderBy(x => x.NUMRNG).OrderBy(x => x.DEBGAR).OrderBy(x => x.FINGAR)
                    //    )
                    //{
                    //    writer.WriteLine(ligne);
                    //}
     
                }
                MessageBox.Show("Fichier trié avec success. ");
            }
            }
    }
    exemple_PRE-DMA-CONTRAT - Copie.xlsx

    Citation Envoyé par fozzeuh Voir le message
    Tu pourrais me fournir un CSV d'exemple pour que je teste ?

  7. #7
    Membre à l'essai
    Homme Profil pro
    Informatique
    Inscrit en
    Janvier 2012
    Messages
    20
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Informatique
    Secteur : Enseignement

    Informations forums :
    Inscription : Janvier 2012
    Messages : 20
    Points : 16
    Points
    16
    Par défaut
    Bonjour dkmix,

    Je te remercie pour ta réponse mais je n'ai pas bien compris ta solution!! désolé je suis débutant en prog :\

    cette partie du code je la mets où? dans mon bouton? cela voudrait-il dire qu'il faudra que je change tout mon code?

    Je te remercie encore une fois.

    Slim025


    Citation Envoyé par dkmix Voir le message
    Bonjour,

    Selon la taille et les perfs souhaités, il est possible de de faire comme ceci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    using (var manager = new CsvManager())
      {
         DataTable dt = new DataTable();
         manager.ReadCsv(dt, "NomDemOnFIchier.csv", false, Encoding.Default,',');
     
           dt.DefaultView.Sort = " ... ";
         ...
         dt.Dispose();
     }
    DataView.Sort

    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
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
     
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
     
    namespace Files.Csv
    {
        /// <summary>
        /// Classe pour gerer les fichiers CSV
        /// </summary>
        public class CsvManager : IDisposable
        {
            private const char SEPARATOR_CHAR = ';';
     
            ~CsvManager()
            {
                // Finalizer calls Dispose(false)
                Dispose(false);
            }
     
            #region "Write"
     
            /// <summary>
            /// Transformation d'un Datatable en fichier CSV.
            /// </summary>
            /// <param name="table">Datatable contenant les infos à écrire.</param>
            /// <param name="fileName">Nom complet du fichier de sortie.</param>
            /// <param name="hasColumnHeader">Spécifie si on utilise la première ligne comme entête.</param>
            /// <param name="separator">Caractère de séparation (par défaut : ';') </param>
            public void WriteCsv(DataTable table, string fileName, bool hasColumnHeader, char separator = SEPARATOR_CHAR)
            {
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
     
                using (Stream sTWritter = File.Create(fileName))
                {
                    WriteCsv(table, sTWritter, hasColumnHeader, separator);
                }
            }
     
            /// <summary>
            /// Transformation d'un Datatable en <see cref="Stream"/>.
            /// </summary>
            /// <param name="table">Datatable contenant les infos à écrire.</param>
            /// <param name="stream">Le <see cref="Stream"/> dans lequel on écrit.</param>
            /// <param name="hasColumnHeader">Spécifie si on utilise la première ligne comme entête.</param>
            /// <param name="separator">Caractère de séparation (par défaut : ';') </param>
            public void WriteCsv(DataTable table, Stream stream, bool hasColumnHeader, char separator = SEPARATOR_CHAR)
            {
                using (var txtWritter = new StreamWriter(stream))
                {
                    WriteCsv(table, txtWritter, hasColumnHeader, separator);
                }
            }
     
            /// <summary>
            /// Transformation d'un Datatable en <see cref="TextWriter"/>.
            /// </summary>
            /// <param name="table">Datatable contenant les infos à écrire.</param>
            /// <param name="writer">Le <see cref="TextWriter"/> dans lequel on écrit.</param>
            /// <param name="hasColumnHeader">Spécifie si on utilise la première ligne comme entête.</param>
            /// <param name="separator">Caractère de séparation (par défaut : ';') </param>
            public void WriteCsv(DataTable table, TextWriter writer, bool hasColumnHeader, char separator = SEPARATOR_CHAR)
            {
                if (hasColumnHeader)
                {
                    for (int index = 0; index <= table.Columns.Count - 1; index++)
                    {
                        if (index > 0)
                        {
                            writer.Write(separator);
                        }
     
                        writer.Write(QuoteText(table.Columns[index].ColumnName, separator));
                    }
     
                    writer.WriteLine();
                }
     
                for (int rowIndex = 0; rowIndex <= table.Rows.Count - 1; rowIndex++)
                {
                    for (int colIndex = 0; colIndex <= table.Columns.Count - 1; colIndex++)
                    {
                        if (colIndex > 0)
                        {
                            writer.Write(separator);
                        }
     
                        writer.Write(QuoteText(Convert.ToString(table.Rows[rowIndex][colIndex], CultureInfo.InvariantCulture), separator));
                    }
     
                    writer.WriteLine();
                }
            }
            #endregion
     
            #region "Read"
     
            /// <summary>
            /// Transformation d'un fichier CSV en <see cref="DataTable"/>
            /// </summary>
            /// <param name="table">Le <see cref="DataTable"/> dans lequel on écrit les données.</param>
            /// <param name="fileName">Nom du fichier CSV pour la lecture des données.</param>
            /// <param name="hasColumnHeader">Spécifie si on utilise la première ligne comme entête.</param>
            /// <param name="encoding">Encodage utilisé</param>
            /// <param name="separator">Caractère de séparation (par défaut : ';') </param>
            /// <param name="deleteLastChar">Suppression du dernier caractère</param>
            public void ReadCsv(DataTable table, string fileName, bool hasColumnHeader, Encoding encoding, char separator = SEPARATOR_CHAR, bool deleteLastChar = false)
            {
                using (Stream st = File.OpenRead(fileName))
                {
                    ReadCsv(table, st, hasColumnHeader, encoding, separator, deleteLastChar);
                }
            }
     
            /// <summary>
            /// Transformation d'un <see cref="Stream"/> en <see cref="DataTable"/>
            /// </summary>
            /// <param name="table">Le <see cref="DataTable"/> dans lequel on écrit les données.</param>
            /// <param name="stream">Le <see cref="Stream"/> utilisé pour la lecture des données.</param>
            /// <param name="hasColumnHeader">Spécifie si on utilise la première ligne comme entête.</param>
            /// <param name="encoding">Encodage utilisé</param>
            /// <param name="separator">Caractère de séparation (par défaut : ';') </param>
            /// <param name="deleteLastChar">Suppression du dernier caractère</param>
            public void ReadCsv(DataTable table, Stream stream, bool hasColumnHeader, Encoding encoding, char separator = SEPARATOR_CHAR, bool deleteLastChar = false)
            {
                using (TextReader txtReader = new StreamReader(stream, encoding))
                {
                    ReadCsv(table, txtReader, hasColumnHeader, separator, deleteLastChar);
                }
            }
     
            /// <summary>
            /// Transformation d'un <see cref="TextReader"/> en <see cref="DataTable"/> .
            /// </summary>
            /// <param name="table">Le <see cref="DataTable"/> dans lequel on écrit les données.</param>
            /// <param name="reader">Le <see cref="TextReader"/> utilisé pour la lecture des données.</param>
            /// <param name="hasColumnHeader">Spécifie si on utilise la première ligne comme entête.</param>
            /// <param name="separator">Caractère de séparation (par défaut : ';') </param>
            /// <param name="deleteLastChar">Suppression du dernier caractère</param>
            public void ReadCsv(DataTable table, TextReader reader, bool hasColumnHeader, char separator = SEPARATOR_CHAR, bool deleteLastChar = false)
            {
                string line = reader.ReadLine();
                if (string.IsNullOrEmpty(line))
                {
                    return;
                }
     
                string[] parts = ReadParts(line, separator, deleteLastChar);
     
                if (hasColumnHeader)
                {
                    foreach (string part in parts)
                    {
                        table.Columns.Add(part, typeof(string));
                    }
     
                    line = reader.ReadLine();
                }
                else
                {
                    foreach (string part in parts)
                    {
                        table.Columns.Add().DataType = typeof(string);
                    }
                }
     
                while (!string.IsNullOrEmpty(line))
                {
                    parts = ReadParts(line, separator);
     
                    DataRow row = table.NewRow();
                    for (int index = 0; index <= parts.Length - 1; index++)
                    {
                        if (parts[index].Equals(separator.ToString()))
                        {
                            parts[index] = string.Empty;
                        }
                        else
                        {
                            row[index] = parts[index];
                        }
                    }
     
                    table.Rows.Add(row);
                    line = reader.ReadLine();
                }
            }
     
            #endregion
     
            /// <summary>
            /// Dispose les ressources
            /// </summary>
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
     
            /// <summary>
            /// Dispose les ressources
            /// </summary>
            /// <param name="disposing">Is Disposing</param>
            protected virtual void Dispose(bool disposing)
            {
                if (disposing)
                {
                    // free managed resources               
                }
            }
     
            #region private
     
            private string[] ReadParts(string line, char separator, bool deletelastChar = false)
            {
                // Suppression du dernier caractère de séparation en cas de csv mal formaté
                if (deletelastChar == true)
                {
                    if (line.EndsWith(separator.ToString()))
                    {
                        line = line.Substring(0, line.Length - 1);
                    }
                }
     
                List<string> parts = new List<string>();
     
                bool inQuotes = false;
                int partIndex = 0;
                int endPartIndex = 0;
                for (int index = 0; index <= line.Length - 1; index++)
                {
                    if (inQuotes)
                    {
                        if (line[index] == '"')
                        {
                            endPartIndex = index - 1;
                            inQuotes = false;
                        }
                        else
                        {
                            endPartIndex = index;
                        }
                    }
                    else
                    {
                        if (line[index] == '"')
                        {
                            partIndex = index + 1;
                            endPartIndex = partIndex;
                            inQuotes = true;
                        }
                        else if (line[index] == separator)
                        {
                            parts.Add(line.Substring(partIndex, endPartIndex - partIndex + 1));
                            partIndex = index + 1;
                            endPartIndex = partIndex;
                        }
                        else
                        {
                            endPartIndex = index;
                        }
                    }
                }
     
                if (!line.Length.Equals(partIndex))
                {
                    parts.Add(line.Substring(partIndex, endPartIndex - partIndex + 1));
                }
                else
                {
                    parts.Add(string.Empty);
                }
     
                return parts.ToArray();
            }
     
            private string QuoteText(object value, char separator)
            {
                if (value == null || Convert.IsDBNull(value))
                {
                    return string.Empty;
                }
     
                string strValue = value.ToString();
                if (strValue.Contains(separator))
                {
                    return "\"" + strValue + "\"";
                }
                else
                {
                    return strValue;
                }
            }
     
            #endregion
        }
    }

Discussions similaires

  1. Tri multiple de fichiers
    Par pepitolover dans le forum Shell et commandes POSIX
    Réponses: 1
    Dernier message: 18/01/2013, 11h33
  2. [CSV] Tri de données dans fichier CSV
    Par PhilippeIEP dans le forum Langage
    Réponses: 6
    Dernier message: 08/10/2008, 11h48
  3. [WD5.5] Tri d'une table fichier.
    Par Thanor dans le forum WinDev
    Réponses: 15
    Dernier message: 30/01/2007, 17h57
  4. Formulaire tri multiple
    Par sheeridan dans le forum IHM
    Réponses: 2
    Dernier message: 26/12/2006, 08h10
  5. Tri multiple (programmeur Perl pas doué inside)
    Par Arioch dans le forum Langage
    Réponses: 5
    Dernier message: 18/07/2006, 13h47

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