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

VB.NET Discussion :

Fichier txt vers excel


Sujet :

VB.NET

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre très actif
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Septembre 2005
    Messages
    151
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Maroc

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Septembre 2005
    Messages : 151
    Par défaut Fichier txt vers excel
    Salut
    dans mon programme je dois importer des données enregistrer dans un fichier txt vers une feuille excel.
    comment faire SVP?
    Merci

  2. #2
    Membre confirmé Avatar de biquet
    Homme Profil pro
    Inscrit en
    Juillet 2003
    Messages
    199
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Juillet 2003
    Messages : 199
    Par défaut
    salut,

    je crois qu'il y a déjà plein de post à ce sujet

    faire une recherche sur le forum

    a+

  3. #3
    Membre très actif
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Septembre 2003
    Messages
    401
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Septembre 2003
    Messages : 401
    Par défaut
    Citation Envoyé par biquet Voir le message
    salut,

    je crois qu'il y a déjà plein de post à ce sujet

    faire une recherche sur le forum

    a+
    Oui biquet à raison et de plus tu ne précises pas la structure de ton fichier txt.
    c'est à dire : Comment son rangé tes données dans le fichier texte.

    Ex :
    Valeur1;Valeur2;Valeur3
    ou
    Valeur1 Valeur2 Valeur3
    ou
    (longeur fixe)
    Valeur1Valeur2Valeur3

    etc....

  4. #4
    Membre extrêmement actif
    Inscrit en
    Avril 2008
    Messages
    2 573
    Détails du profil
    Informations personnelles :
    Âge : 65

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 573
    Par défaut Fichier texte vers Excel
    bonjour
    Le moyen le plus simple de l'injecter dans un classeur excel par interop est definir ton ton type de fichier texte(delimited avec virgule,point-virgule , ou à largeur fixe...) et ensuite un tableau de string suffit.
    Par code ca donne ca :
    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
     
     
    'Il faut un Tableau de String ce qui permet de copier par une seule 
    'instruction ce tableau dans un range destination global
    '(copies par boucle prennent plus de temps si le fichier texte comporte 
    'beaucoup de donnnees)
    Imports System
    Imports System.IO
    Imports System.Windows
    Imports OXL = Microsoft.Office.Interop.Excel
     
     
    Public Class frmTexteExcel
        Private appExcel As OXL.Application
        Private wbk As OXL.Workbook
        Private feuilleExcel As OXL.Worksheet
        Private rngGlobal As OXL.Range
        Private tableString As String(,)
     
     
        Private Sub btnOuvrirFichier_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOuvrirFichier.Click
     
            Dim fichierChemin As String = ""
            Me.OpenFileDialog1.Filter = "Fichier Texte(*.txt)|*.txt"
            If Me.OpenFileDialog1.ShowDialog = DialogResult.OK Then
                fichierChemin = Me.OpenFileDialog1.FileName
                If Len(fichierChemin) = 0 Then
                    MessageBox.Show("erreur fichier...")
                    Exit Sub
                Else
                    tableString = LitFichier(fichierChemin, tableString)
                    Call TransfertVersExcel(tableString)
                End If
            End If
        End Sub
        'Lit le Fichier avec separateur point virgule
        Private Function LitFichier(ByVal cheminfichier As String, ByVal objString As String(,)) As String(,)
            Dim strLigne As String()
            Dim nbCol As Integer = 0
            Dim nbLig As Integer = 0
            Using monReader As New  _
            Microsoft.VisualBasic.FileIO.TextFieldParser(cheminfichier)
                monReader.TextFieldType = FileIO.FieldType.Delimited
                monReader.SetDelimiters(";")
                While Not monReader.EndOfData
                    Try
                        strLigne = monReader.ReadFields()
                        nbCol = 0
                        For Each champCourant As String In strLigne
                            nbCol = nbCol + 1
                        Next
                        'ligne suivante
                        nbLig = nbLig + 1
                    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                        MsgBox("Ligne " & ex.Message & _
                        "non valide,sera saute....")
                    End Try
                End While
            End Using
            ReDim Preserve objString(nbLig, nbCol)
            Using monReader As New  _
           Microsoft.VisualBasic.FileIO.TextFieldParser(cheminfichier)
                monReader.TextFieldType = FileIO.FieldType.Delimited
                monReader.SetDelimiters(";")
     
                Dim numLig As Integer = 0
                While Not monReader.EndOfData
                    Try
                        strLigne = monReader.ReadFields()
                        Dim numCol As Integer = 0
                        For Each champCourant As String In strLigne
                            objString(numLig, numCol) = champCourant                        'champ suivant
                            numCol = numCol + 1
                        Next
                        'ligne suivante
                        numLig = numLig + 1
                    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                        MsgBox("Ligne " & ex.Message & _
                        "non valide,sera saute....")
                    End Try
                End While
                   End Using
            Return objString
        End Function
        Private Sub TransfertVersExcel(ByVal objString As String(,))
            'Si Excel est ouvert le fermer
            If appExcel IsNot Nothing Then
                appExcel.Quit()
                appExcel = Nothing
            End If
            appExcel = New OXL.Application
            wbk = appExcel.Workbooks.Add()
            wbk.Activate()
     
            feuilleExcel = wbk.Worksheets(1)
            'Copie en bloc vers un Range Global
            Dim celluleDepart As OXL.Range = feuilleExcel.Cells(1, 1)
            Dim celluleFin As OXL.Range = feuilleExcel.Cells(objString.GetUpperBound(0) + 1, objString.GetUpperBound(1) + 1)
            rngGlobal = feuilleExcel.Range(celluleDepart, celluleFin)
            rngGlobal.Value = objString
            'Mise en forme du Range
            rngGlobal.Interior.Color = ColorTranslator.ToOle(Color.Yellow)
            rngGlobal.BorderAround(LineStyle:=OXL.XlLineStyle.xlDouble, Weight:=OXL.XlBorderWeight.xlMedium, ColorIndex:=Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Color:=ColorTranslator.ToOle(Color.Yellow))
            rngGlobal.Font.Name = "Times New Roman"
            rngGlobal.Font.Size = 12
            rngGlobal.Font.Bold = True
            rngGlobal.Font.Color = ColorTranslator.ToOle(Color.Red)
            'Affiche Excel
            appExcel.Visible = True
     
        End Sub
        'Enregistre le fichier avec separateur point virgule
        Private Sub btnEnregFichier_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnregFichier.Click
            Dim fichierChemin As String = ""
            Me.SaveFileDialog1.Filter = "Fichier Texte(*.txt)|*.txt"
            If Me.SaveFileDialog1.ShowDialog = DialogResult.OK Then
                fichierChemin = Me.SaveFileDialog1.FileName
                If Len(fichierChemin) = 0 Then
                    MessageBox.Show("erreur fichier...")
                    Exit Sub
                Else
                    If appExcel IsNot Nothing Then
                        Call EcritFichier(fichierChemin)
                    Else
                        MsgBox("Il n' y a aucune donne à sauvegarder Recharger Classeur SVP....")
                    End If
     
                End If
            End If
        End Sub
        'Ecrit Classeur vers Fichier Texte
        Private Sub EcritFichier(ByVal cheminfichier As String)
            Dim MonWriter As System.IO.StreamWriter = New System.IO.StreamWriter(cheminfichier, False)
            Dim strLigne As String = ""
            Dim sep As String = ";"
     
            Try
                For i As Integer = 1 To rngGlobal.Rows.Count - 1
                    For j As Integer = 1 To rngGlobal.Columns.Count - 1
                        strLigne = strLigne & rngGlobal.Item(i, j).value & sep
                    Next
                    MonWriter.WriteLine(strLigne)
                    strLigne = ""
                Next
                MonWriter.Close()
            Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                MsgBox("Ligne " & ex.Message & _
                "non valide,sera saute....")
            End Try
     
        End Sub
        Private Sub btnFermeClasseur_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFermeClasseur.Click
            rngGlobal = Nothing
            wbk.Close(SaveChanges:=False)
            wbk = Nothing
            appExcel.Quit()
            appExcel = Nothing
        End Sub
    End Class
    bien sur comme dit par biquet si tu ne te contente pas de excel,mais tu veux virer le contenu ailleurs ,par exemple dans une BD ,ou faire des calculs sur les donnees il vaut mieux "mapper" (faire correspondre un à un) tes colonnes vers les proprietes d'une classe ou d'une datable .
    Regarde les post de biquet.
    BON CODE....

  5. #5
    Membre extrêmement actif
    Inscrit en
    Avril 2008
    Messages
    2 573
    Détails du profil
    Informations personnelles :
    Âge : 65

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 573
    Par défaut Fichier texte vers Excel
    Rebonjour
    ci-joint fichier .rar du projet exemple avec le fichier texte pour tester l'exemple.

  6. #6
    Membre très actif
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Septembre 2005
    Messages
    151
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Maroc

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Septembre 2005
    Messages : 151
    Par défaut
    Merci les amis pour votre aide

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

Discussions similaires

  1. [Toutes versions] lecture et redirection de données d'un fichier .txt vers une feuille Excel
    Par Max_F dans le forum Excel
    Réponses: 1
    Dernier message: 30/10/2014, 22h46
  2. [XL-2007] fichier en extension .txt vers excel
    Par Debutant10 dans le forum Conception
    Réponses: 1
    Dernier message: 09/11/2011, 09h15
  3. Réponses: 0
    Dernier message: 07/06/2010, 16h01
  4. [VBA Excel] Extraction de données fichier txt vers Excel et mise en forme
    Par newcodeur dans le forum Macros et VBA Excel
    Réponses: 0
    Dernier message: 23/05/2008, 11h45
  5. importation d'un fichier texte vers excel
    Par darkpocket dans le forum Macros et VBA Excel
    Réponses: 3
    Dernier message: 07/01/2005, 11h47

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