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 :

améliorer un code


Sujet :

VB.NET

  1. #1
    Membre confirmé
    Femme Profil pro
    Enseignant
    Inscrit en
    Avril 2007
    Messages
    130
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Enseignant
    Secteur : Enseignement

    Informations forums :
    Inscription : Avril 2007
    Messages : 130
    Par défaut améliorer un code
    Bonsoir
    pour générer un aperçu d'un fichier excel, j'utilise l'algorithme suivant:
    -j'ouvre le fichier
    -j’accède à la base de données
    -je remplis le fichiers par les données nécessaires
    -j'affiche l'aperçu
    le problème est que l'affichage du résultat prend presque 15 secondes
    comment améliorer le 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
    123
    124
    125
     Private Sub FicheSuivimenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FicheSuivimenu.Click
            'Déclaration des variables
            Dim appExcel As New Excel.Application 'Application Excel
            Dim wbExcel As Excel.Workbook 'Classeur Excel
            Dim wsExcel As Excel.Worksheet 'Feuille Excel
            Try
                'Ouverture de l'application
                appExcel = CreateObject("Excel.Application")
                'Ouverture d'un fichier Excel
     
     
                wbExcel = appExcel.Workbooks.Open(Application.StartupPath & "\fiche_intervention.xls")
                'wsExcel correspond à la première feuille du fichier
                wsExcel = wbExcel.Worksheets(1)
     
                wbExcel = appExcel.ActiveWorkbook
                'Récupération de la feuille par défaut
                wsExcel = wbExcel.ActiveSheet
     
                Dim MyDataReader As MySqlDataReader
                Dim MyConString As String = "SERVER=localhost;" + _
            "DATABASE=prj;" + "UID=root;" + "PASSWORD=;"
     
                Dim idclt, x As Integer
                Dim con As New MySqlConnection(MyConString) '
                con.Open()
                Dim MyCommand As New MySqlCommand()
                MyCommand.Connection = con
     
     
                For Each myShp As Excel.Shape In wsExcel.Shapes
                    If myShp.Name = "clt" Then
                        myShp.TextFrame.Characters.Text = frmGestionClt.DTGclient.CurrentRow.Cells(0).Value
                        myShp.TextFrame.Characters.Font.Size = 10
                        myShp.TextFrame.Characters.Font.Name = "Arial"
                    ElseIf myShp.Name = "int" Then
                        myShp.TextFrame.Characters.Text = frmGestionClt.DTGIntervention.CurrentRow.Cells(0).Value
                        myShp.TextFrame.Characters.Font.Size = 10
                        myShp.TextFrame.Characters.Font.Name = "Arial"
     
                    End If
                Next
     
                wsExcel.Cells(7, 1).value = frmGestionClt.DTGclient.CurrentRow.Cells(1).Value
     
                'récupérer  id_client 
                MyCommand.CommandText = "select Id_client from client where Numero_de_client=" & "'" & frmGestionClt.client & "'"
                MyDataReader = MyCommand.ExecuteReader()
                x = MyDataReader.Read()
                idclt = MyDataReader.GetInt32(0)
                MyDataReader.Close()
     
                Dim lig As Integer
                ' Charger la datagridview
                MyCommand.CommandText = "select `Numero_du_poste`, `Type de nuisible`, `Batiment`, `Niveau`, `Nom des locaux`, Id_poste from poste  where  Id_client=" & "'" & idclt & "'   order by `Batiment`, `Niveau`, `Numero_du_poste`"
                ' z = MyCommand.ExecuteNonQuery
                'MsgBox(z)
                MyDataReader = MyCommand.ExecuteReader()
     
                Dim od As Integer
                od = 0
                Dim savniv, savbat As String
                savniv = ""
                savbat = ""
                lig = 15
                While MyDataReader.Read()
     
                    If MyDataReader.GetString(2) <> "<aucun>" And savbat <> MyDataReader.GetString(2) And savniv <> MyDataReader.GetString(3) Then
                        savbat = MyDataReader.GetString(2)
                        savniv = MyDataReader.GetString(3)
                        wsExcel.Range("A" & lig & ":BE" & lig).Merge(False)
                        wsExcel.Range("A" & lig & ":BE" & lig).BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic)
                        wsExcel.Cells(lig, 1).value = "Batiment: " & savbat
                        lig = lig + 1
                        wsExcel.Range("A" & lig & ":BE" & lig).Merge(False)
                        wsExcel.Cells(lig, 1).value = "              Niveau : " & savniv
                        wsExcel.Range("A" & lig & ":BE" & lig).BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic)
                        lig = lig + 1
                    ElseIf MyDataReader.GetString(2) <> "<aucun>" And savbat <> MyDataReader.GetString(2) And savniv = MyDataReader.GetString(3) Then
                        savniv = MyDataReader.GetString(3)
                        wsExcel.Range("A" & lig & ":BE" & lig).Merge(False)
                        wsExcel.Cells(lig, 1).value = "Batiment: " & MyDataReader.GetString(2)
                        wsExcel.Range("A" & lig & ":BE" & lig).BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic)
                        lig = lig + 1
                        wsExcel.Range("A" & lig & ":BE" & lig).Merge(False)
                        wsExcel.Cells(lig, 1).value = "              Niveau : " & MyDataReader.GetString(3)
                        wsExcel.Range("A" & lig & ":BE" & lig).BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic)
                        lig = lig + 1
     
                    ElseIf MyDataReader.GetString(3) <> "<aucun>" And savniv <> MyDataReader.GetString(3) Then
                        wsExcel.Range("A" & lig & ":BE" & lig).Merge(False)
                        wsExcel.Cells(lig, 1).value = "              Niveau : " & MyDataReader.GetString(3)
                        wsExcel.Range("A" & lig & ":BE" & lig).BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic)
                        lig = lig + 1
     
                    End If
                    wsExcel.Cells(lig, 19).value = MyDataReader.GetString(4)
                    wsExcel.Cells(lig, 20).value = MyDataReader.GetString(0)
                    wsExcel.Cells(lig, 21).value = MyDataReader.GetString(1)
     
                    For Each cellule In wsExcel.Range("A" & lig & ":BE" & lig)
                        cellule.Borders.Weight = Excel.XlBorderWeight.xlThin
                    Next
     
                    If lig = 35 Then
     
                    End If
     
                    lig = lig + 1
                End While
                MyDataReader.Close()
                con.Close()
                appExcel.Visible = True
                wsExcel.PrintOut(1, 4, 1, True, , , , )
                Dim p As String
                p = Environment.GetFolderPath(System.Environment.SpecialFolder.Personal).ToString & "\Rapport\"
                MsgBox(p)
                wsExcel.SaveAs("Fiche de suivi du client ", , , , , , , , , p)
                wbExcel.Close()
                appExcel.Quit()
     
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub

  2. #2
    Expert éminent Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 194
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 194
    Par défaut
    remplir (ou lire) un fichier excel par interop est en effet lent
    il y a des solutions plus performantes
    tout d'abord, ado.net gère excel, il est donc possible de manipuler les données d'un fichier excel comme une base de données (select nomcol1,nomcol2 from nomsheet, create table => create sheet, insert into sheet1 etc...)
    et je crois même qu'il exite un moyen depuis sql server d'accéder à un fichier excel à peu près de la même manière
    ce qui ferait insert into excel.sheet1 select * from table1

    je ne connais pas la syntaxe (si elle existe, m'enfin il me semble l'avoir vu trainer par ici) pour accéder à un fichier excel depuis sql server)
    et pour ado.net (donc depuis vb.net) il faut utiliser system.data.oledb et donc oledbconnection (le connectstring est trouvable sur le net, et précise que c'est un fichier excel et son chemin)
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  3. #3
    Membre éprouvé
    Avatar de Pelote2012
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mars 2008
    Messages
    925
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Haute Vienne (Limousin)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Mars 2008
    Messages : 925
    Billets dans le blog
    2
    Par défaut
    Si tu vas sur Goolgle en tapant Excel vb.net tu aura plein de nouvelles idées

    Quand tu aura trouver une syntaxe plus performante, n'hésite pas à la parrtager

  4. #4
    Membre confirmé
    Femme Profil pro
    Enseignant
    Inscrit en
    Avril 2007
    Messages
    130
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Enseignant
    Secteur : Enseignement

    Informations forums :
    Inscription : Avril 2007
    Messages : 130
    Par défaut
    bonjour;

    Voici un lien qui présente les méthodes d'export de données vers excel
    http://support.microsoft.com/kb/247412/fr

    j'ai choisi cette méthode mais je sais pas que mettre dans datasource pour l'adapter à mon projet qui utilise MySQL

    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
     'Create a new workbook in Excel
       Dim oExcel As Object
       Dim oBook As Object
       Dim oSheet As Object
       Set oExcel = CreateObject("Excel.Application")
       Set oBook = oExcel.Workbooks.Add
       Set oSheet = oBook.Worksheets(1)
     
       'Create the QueryTable
       Dim sNWind As String
       sNWind = _
          "C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb"
       Dim oQryTable As Object
       Set oQryTable = oSheet.QueryTables.Add( _
       "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
          sNWind & ";", oSheet.Range("A1"), "Select * from Orders")
       oQryTable.RefreshStyle = xlInsertEntireRows
       oQryTable.Refresh False
     
       'Save the Workbook and Quit Excel
       oBook.SaveAs "C:\Book1.xls"
       oExcel.Quit

  5. #5
    Membre confirmé
    Femme Profil pro
    Enseignant
    Inscrit en
    Avril 2007
    Messages
    130
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Enseignant
    Secteur : Enseignement

    Informations forums :
    Inscription : Avril 2007
    Messages : 130
    Par défaut
    enfin c'est résolu
    merci pour vos indication et votre aide

    voici le 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
     With wsExcel.QueryTables.Add(Connection:="ODBC;DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost; DATABASE=prj; UID=root;" + "PASSWORD=;", Destination:=wsExcel.Range("B1"), Sql:="SELECT  `Numero_de_client` , `Nom juridique` , `Adresse des locaux` , `Type de contrat` , `Code postal` , Ville FROM client order by `Nom juridique`")
                    .FieldNames = False
                    .RowNumbers = False
                    .FillAdjacentFormulas = False
                    .PreserveFormatting = True
                    .RefreshOnFileOpen = False
                    .BackgroundQuery = False
                    .RefreshStyle = Excel.XlCellInsertionMode.xlOverwriteCells
                    .SavePassword = True
                    .SaveData = True
                    .AdjustColumnWidth = True
                    .RefreshPeriod = 0
                    .PreserveColumnInfo = True
                    .Refresh(BackgroundQuery:=True)
                End With

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

Discussions similaires

  1. Amélioration de code
    Par Devilju69 dans le forum Langage
    Réponses: 3
    Dernier message: 07/10/2008, 15h01
  2. Optimisations et Améliorations de code
    Par womannosky dans le forum Langage
    Réponses: 19
    Dernier message: 02/07/2008, 15h05
  3. [Optimisation]Peut-on améliorer ce code ?
    Par progfou dans le forum Algorithmes et structures de données
    Réponses: 6
    Dernier message: 09/08/2007, 15h43
  4. [Tableaux] Amélioration de code (if)
    Par Sir Tengu dans le forum Langage
    Réponses: 3
    Dernier message: 24/12/2006, 00h26
  5. [Sécurité] Comment amélioré mon code ?
    Par Nadd dans le forum Langage
    Réponses: 14
    Dernier message: 03/03/2006, 20h13

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