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 :

OleDb Excel texte de plus de 255 caractères tronqué


Sujet :

C#

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Novembre 2007
    Messages
    95
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2007
    Messages : 95
    Points : 52
    Points
    52
    Par défaut OleDb Excel texte de plus de 255 caractères tronqué
    Bonjour,

    Tous est dans le titre j'importe des données d'un fichier excel via OleDb cependant, je viens de m'apercevoir que que si une cellule contenait plus de 255 caractère alors celle-ci était tronqué à 255. J'ai fait des recherche pour contourner le problèmes mais je n'ai rien trouvé de concluant. Est ce qu'il y a un moyen d'importer des cellules de plus de 255 caractères ?

    Voilà la classe bien utile que j'utilise.
    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
    #region Imports
     
    using System;
    using System.Data;
    using System.Data.OleDb;
    using System.Diagnostics;
     
    #endregion
     
        /// <summary>
        /// A client which interfaces to excel work books
        /// </summary>
        public class MicrosoftExcelClient
        {
     
            #region Variable Declarations
     
            /// <summary>
            /// Current message from the client
            /// </summary>
            string m_CurrentMessage = "";
     
            /// <summary>
            /// The file path for the source excel book
            /// </summary>
            string m_SourceFileName;
     
            /// <summary>
            /// Connects to the source excel workbook
            /// </summary>
            OleDbConnection m_ConnectionToExcelBook;
     
            /// <summary>
            /// Reads the data from the document to a System.Data object
            /// </summary>
            OleDbDataAdapter m_AdapterForExcelBook;
     
            #endregion
     
            #region Constructor Logic
     
            /// <summary>
            /// Parameterized constructor .. specifies path
            /// </summary>
            /// <param name="iSourceFileName">The source filename</param>
            public MicrosoftExcelClient(string iSourceFileName)
            {
                this.m_SourceFileName = iSourceFileName;
            }
     
            #endregion
     
            #region Properties
     
            /// <summary>
            /// Gets the current messages from the client
            /// </summary>
            public string CurrentMessage
            {
                get { return this.m_CurrentMessage; }
            }
     
            /// <summary>
            /// Property that gets / sets the current source excel book
            /// </summary>
            public string FileName
            {
                get { return this.m_SourceFileName; }
                set { this.m_SourceFileName = value; }
            }
     
            #endregion
     
            #region query methods
     
            /// <summary>
            /// Runs a non query database command such as UPDATE , INSERT or DELETE
            /// </summary>
            /// <param name="iQuery">The required query</param>
            /// <returns></returns>
            public bool runNonQuery(string iQuery)
            {
                try
                {
                    //Declares new Command to query
                    OleDbCommand selectCommand = new OleDbCommand(iQuery);
     
                    //Declares new connection to an Excel workbook
                    selectCommand.Connection = this.m_ConnectionToExcelBook;
     
                    //Data adapter
                    this.m_AdapterForExcelBook = new OleDbDataAdapter();
     
                    m_AdapterForExcelBook.UpdateCommand = selectCommand;
                    selectCommand.ExecuteNonQuery();
     
                    return true;
     
                }
                catch (Exception ex)
                {
                    this.m_CurrentMessage = "Erreur " + ex.Message;
                    return false;
                }
            }
     
            /// <summary>
            /// Reads data as per the user query
            /// </summary>
            /// <param name="iQuery">The speicfic Query</param>
            /// <returns>Returns a dataTable, with results from query</returns>
            public DataTable readForSpecificQuery(string iQuery)
            {
                try
                {
                    //Declares new dataTable, which will be returned filled from query
                    DataTable returnDataObject = new DataTable();
     
                    //Command
                    OleDbCommand selectCommand = new OleDbCommand(iQuery);
                    selectCommand.Connection = this.m_ConnectionToExcelBook;
     
                    //DataAdapter for our excel workbook
                    this.m_AdapterForExcelBook = new OleDbDataAdapter();
     
                    //Applies the Select command to the oledbdataadapter and fills it
                    this.m_AdapterForExcelBook.SelectCommand = selectCommand;
                    this.m_AdapterForExcelBook.Fill(returnDataObject);
     
                    //Sets a success message if query returned good results
                    this.m_CurrentMessage = "Succès - " + returnDataObject.Rows.Count + " records importés ";
     
                    return returnDataObject;
                }
                catch (Exception ex)
                {
                    //Displays an error message in the statut bar.
                    this.m_CurrentMessage = "ERREUR: " + ex.Message;
                    return null;
                }
            }
     
            /// <summary>
            /// Reads an entire excel sheet from an opened excel workbook
            /// </summary>
            /// <param name="iSheetName">The name of the excel worksheet</param>
            /// <returns>Returns a DataTable filled</returns>
            public DataTable readEntireSheet(string iSheetName)
            {
                try
                {
                    //Declares new DataTable to be returned
                    DataTable returnDataObject = new DataTable();
     
                    //New Command for our Select
                    OleDbCommand selectCommand = new OleDbCommand("select * from [" + iSheetName + "$]");
                    selectCommand.Connection = this.m_ConnectionToExcelBook;
     
                    this.m_AdapterForExcelBook = new OleDbDataAdapter();
     
                    this.m_AdapterForExcelBook.SelectCommand = selectCommand;
                    this.m_AdapterForExcelBook.Fill(returnDataObject);
     
                    this.m_CurrentMessage = "Succès - " + returnDataObject.Rows.Count + " records importés ";
     
                    return returnDataObject;
     
                }
                catch (Exception ex)
                {
                    //Displays error message
                    this.m_CurrentMessage = "ERREUR " + ex.Message;
                    return null;
                }
     
            }
     
            #endregion
     
            #region Open read connection
     
            /// <summary>
            /// Opens a READ ONLY connection to the source excel document
            /// </summary>
            /// <returns>Returns nothing</returns>
            public void openConnection()
            {
                String chaineConnexion = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + this.m_SourceFileName + ";Extended Properties=\"Excel 8.0;IMEX=1\"";
     
                try
                {
                    this.m_ConnectionToExcelBook = new OleDbConnection(chaineConnexion);
                    this.m_ConnectionToExcelBook.Open();
                    this.m_CurrentMessage = "Succès - La connexion à la source a été établie";
                }
                catch (Exception ex)
                {
                    //If Excel file didn't open, return an error message
                    this.m_CurrentMessage = "Erreur lors de l'ouverture du fichier";
                }
            }
     
            /// <summary>
            /// Closes the connection to the source excel document
            /// </summary>
            /// <returns></returns>
     
            #endregion
     
            #region open write connection
            /// <summary>
            /// Opens a WRITE connection to the source excel document.
            /// </summary>
            /// <returns></returns>
            public void openWriteConnection()
            {
                String chaineConnexion = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + this.m_SourceFileName + ";Extended Properties=\"Excel 8.0;IMEX=2\"";
     
                try
                {
                    this.m_ConnectionToExcelBook = new OleDbConnection(chaineConnexion);
                    this.m_ConnectionToExcelBook.Open();
                    this.m_CurrentMessage = "Succès - La connexion à la source a été établie";
                }
                catch (Exception ex)
                {
                    //Error message if connection didn't open
                    this.m_CurrentMessage = "Erreur lors de l'ouverture du fichier";
                }
            }
            #endregion
     
            #region Close connection
     
        public bool closeConnection()
        {
            try
            {
                this.m_ConnectionToExcelBook.Close();
                this.m_CurrentMessage = "Succès - Connection fermée";
            }
            catch (Exception ex)
            {
                //Error message if closing didn't success
                this.m_CurrentMessage = "ERREUR " + ex.Message;
                return false;
            }
            return true;
        }
     
        #endregion
    }
    Voila le bout de code qui m'affiche mon fichier le fichier Excel dans ma GrindView.

    page aspx :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
     <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
                Text="valider" /><br />
    Code behind :
    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
     
    String TempFileName = "/WINDOWS/Temp/" ;
     
     
            HttpPostedFile file = Request.Files["FileUpload1"];
            file.SaveAs(TempFileName + file.FileName);
     
            Page.Session["fichier1"] = file.FileName;
     
            msExcelClient = new MicrosoftExcelClient(TempFileName + file.FileName);
            msExcelClient.openConnection();
            DataTable result = msExcelClient.readForSpecificQuery("SELECT * FROM [Catalogue 2009$]");
            msExcelClient.closeConnection();
     
            dg.DataSource = result;
            dg.DataBind();
    Je pensais que mes cellules étaient tronquées lors de mon bind() pour alléger l'affichage ou quelque chose du genre mais j'ai essayé d'afficher le contenu de la datatable retourné eet c'est le meme retour tronqué ...


    Merci d'avance pour votre aide.

    Cordialement

    Pierre

  2. #2
    Rédacteur/Modérateur
    Avatar de Skalp
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2006
    Messages
    1 694
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2006
    Messages : 1 694
    Points : 2 927
    Points
    2 927
    Par défaut
    Je n'arrive pas à reproduire ce comportement.
    Envoie-moi le fichier Excel, la réponse s'y trouve peut-être.

    [EDIT]
    Pour déterminer le format des colonnes Excel se base sur les 8 premières lignes.
    Par défaut, il attribue 255 caractères max pour la taille maxi. Ainsi, si les 8 premières cellules d'une colonne contiennent moins de 255 caractères, cette limitation sera attribuée à toute la colonne.

    Pour lever cette limitation des 8 premières lignes, il faut aller modifier la clé de registre suivante : TypeGuessRows dans HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel pour y mettre 0 au lieu de 8 (peut diminuer les performances).

    Citation Envoyé par http://connectionstrings.com/excel
    Check out the [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel] located registry REG_DWORD "TypeGuessRows". That's the key to not letting Excel use only the first 8 rows to guess the columns data type. Set this value to 0 to scan all rows. This might hurt performance.
    [/EDIT]

  3. #3
    Membre du Club
    Profil pro
    Inscrit en
    Novembre 2007
    Messages
    95
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2007
    Messages : 95
    Points : 52
    Points
    52
    Par défaut
    Yes !!!
    Merci pour ton aide qui m'aura été vraiment précieuse, je vais pouvoir oublier ma macro qui scindait mes champ puis les re-concaténait.
    En tout cas un grand merci a toi Skalp !!!

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

Discussions similaires

  1. [Toutes versions] Calcul et export (Table ou Excel) d'un champ de plus de 255 caractères
    Par SylvainM dans le forum Requêtes et SQL.
    Réponses: 5
    Dernier message: 28/05/2015, 12h02
  2. Réponses: 2
    Dernier message: 02/09/2014, 12h58
  3. Réponses: 1
    Dernier message: 27/02/2012, 00h03
  4. Table vers Excel mémo de plus de 255 Caractères
    Par Roller0022 dans le forum WinDev
    Réponses: 1
    Dernier message: 05/06/2009, 13h12
  5. SQL de plus de 255 caractères dans un recordset
    Par acama dans le forum Requêtes et SQL.
    Réponses: 11
    Dernier message: 05/01/2006, 15h50

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