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 :

DatagridView Vers Excel


Sujet :

VB.NET

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Juillet 2010
    Messages
    8
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2010
    Messages : 8
    Par défaut DatagridView Vers Excel
    Bonjour à tous,
    Je cherche à exporter le contenu de mon datagrid vers un fichier excel.


    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
     
    Dim xlsapp As Microsoft.Office.Interop.Excel.Application
            Dim Xlsbook As Microsoft.Office.Interop.Excel.Workbook
            Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
            Dim misValue As Object = System.Reflection.Missing.Value
            Dim i As Integer
            Dim j As Integer
     
            xlsapp = New Excel.ApplicationClass
            Xlsbook = xlsapp.Workbooks.Add(misValue)
     
     
            xlWorkSheet = Xlsbook.Sheets("sheets1")
     
     
     
            For i = 0 To DataGridView1.RowCount - 2
                For j = 0 To DataGridView1.ColumnCount - 1
                    xlWorkSheet.Cells(i + 1, j + 1) = _
                        DataGridView1(j, i).Value.ToString()
                Next
            Next
     
            xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
            Xlsbook.Close()
            xlsapp.Quit()
     
            releaseObject(xlsapp)
            releaseObject(Xlsbook)
            releaseObject(xlWorkSheet)
     
            MsgBox("You can find the file C:\vbexcel.xlsx")
        End Sub
     
        Private Sub releaseObject(ByVal obj As Object)
            Try
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
                obj = Nothing
            Catch ex As Exception
                obj = Nothing
            Finally
                GC.Collect()
            End Try
        End Sub
    End Class

    Simplement je n'arrive pas a créer la feuille "sheets1", j'obtiens l'erreur :


    Index non valide. (Exception de HRESULT : 0x8002000B (DISP_E_BADINDEX))
    à la ligne

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
     
        xlWorkSheet = Xlsbook.Sheets("sheets1")
    Si quelqu'un à une idée...

  2. #2
    Expert confirmé
    Homme Profil pro
    Inscrit en
    Août 2010
    Messages
    3 453
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Août 2010
    Messages : 3 453
    Par défaut
    Bonjour,

    Tu utilise le nom "Sheet1" pour la version Anglaise mais si tu a Excel en Français, utilise "Feuil1" ou alors si il y a un doute utilise son index :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    xlWorkSheet = Xlsbook.Sheets(1)
    Bonne journée

    [EDIT]
    Oups, je suis allé trop vite, tu veux créér la feuille donc :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    xlWorksheet = Xlsbook.Worksheets.Add()
    xlWorksheet.Name = "Sheet1"
    [/EDIT]

  3. #3
    Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2011
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Côte d'Ivoire

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2011
    Messages : 7
    Par défaut
    ce code ma beaucoup aidé surtout avec la correction de @Theze mais le Problème c'est qu'il n'exporte pas l'entête de chaque colonne du datagriedwiew sous Excel c'est a dire les Header , si quelqu'un peut m'aider !!!

  4. #4
    Membre Expert
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    700
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 700
    Par défaut
    Bonsoir,
    tu peux t'inspirer de ce bout de code ( je n'ai pas retrouvé la source) :
    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
            Dim c, l As Integer
            Dim xl As New xls.Application
     
            xl.Workbooks.Add()
     
            For c = 0 To DgvResult.Columns.Count - 1
                ' +++++ j'affiche sur la 1ere ligne, les noms des colonnes du Datagridview (DgvResult).
                '*** Cast de la cellule pour y accéder depuis VB.NET strict.
                Dim castRange As xls.Range = CType(xl.Cells(1, c + 1), xls.Range)
     
                Select Case c + 1
                    Case 1 : castRange.ColumnWidth = 30
                    Case 2 : castRange.ColumnWidth = 15
                    Case 3 : castRange.ColumnWidth = 40
                        ' ETC....
                End Select
                '' *** ou faire un calcul savant 
                'castRange.ColumnWidth = DgvResult.Columns(c).Width / 5
     
                castRange.Borders.Color = RGB(255, 0, 0)
                castRange.Borders.Weight = xls.XlBorderWeight.xlThick
                castRange.Borders.LineStyle = xls.XlLineStyle.xlDouble
     
                castRange.Interior.Color = 10092543
                castRange.HorizontalAlignment = xls.XlHAlign.xlHAlignCenter
                castRange.Font.Size = 14
                castRange.Font.Color = RGB(0, 0, 255)
                castRange.Font.Bold = True
                castRange.Value = DgvResult.Columns(c).HeaderText
            Next
     
            ' +++++ je remplis les cellules du fichier Excel avec les valeurs de DgvResult à partir de la 2ième ligne (l+2). 
            For l = 0 To DgvResult.Rows.Count - 1
                For c = 0 To DgvResult.Columns.Count - 1
                    Dim castRange As xls.Range = CType(xl.Cells(l + 2, c + 1), xls.Range)
     
                    castRange.Borders(xls.XlBordersIndex.xlEdgeLeft).LineStyle = xls.XlLineStyle.xlContinuous
                    castRange.Borders(xls.XlBordersIndex.xlEdgeLeft).Color = RGB(255, 0, 0)
                    castRange.Borders(xls.XlBordersIndex.xlEdgeRight).LineStyle = xls.XlLineStyle.xlContinuous
                    castRange.Borders(xls.XlBordersIndex.xlEdgeRight).Color = RGB(255, 0, 0)
                    castRange.Value = DgvResult.Rows(l).Cells(c).Value
                    If l = DgvResult.Rows.Count - 1 Then
                        castRange.Borders(xls.XlBordersIndex.xlEdgeBottom).LineStyle = xls.XlLineStyle.xlContinuous
                        castRange.Borders(xls.XlBordersIndex.xlEdgeBottom).Color = RGB(255, 0, 0)
                    End If
                Next
            Next
            '*** A placer à la fin pour éviter de visualiser le temps de chargement.
            xl.Visible = True
    Nb : le package importé étant le suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Imports xls = Microsoft.Office.Interop.Excel
    nb : il y a pas mal de choses pour les formats que tu pourras laissez tomber.

  5. #5
    Membre averti
    Homme Profil pro
    Inscrit en
    Octobre 2012
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2012
    Messages : 15
    Par défaut
    Bonjour à tous,

    Je déterre un vieux sujet car j'ai utilisé le bout de code de chrismonoye qui marche très bien lorsque je l'utilise avec excel 2013 mais qui plante lorsque je lance l'application sur un poste avec excel 2000.

    Le blocage se fait sur ces lignes :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    castRange.Value = DgvResult.Columns(c).HeaderText
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    castRange.Value = DgvResult.Rows(l).Cells(c).Value
    avec ce message d'erreur :
    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
    See the end of this message for details on invoking 
    just-in-time (JIT) debugging instead of this dialog box.
     
    ************** Exception Text **************
    System.Runtime.InteropServices.COMException (0x80020011): Ne gère pas les groupes. (Exception from HRESULT: 0x80020011 (DISP_E_NOTACOLLECTION))
       at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
       at Microsoft.Office.Interop.Excel.Range.set_Value(Object RangeValueDataType, Object Param)
       at Action2015.Form5.Button7_Click(Object sender, EventArgs e) in C:\Users\FAB\Documents\Visual Studio 2013\Projects\Action2015\Action2015\Form5.vb:line 117
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
     
     
    ************** Loaded Assemblies **************
    mscorlib
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1026 (RTMGDR.030319-1000)
        CodeBase: file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/mscorlib.dll
    ----------------------------------------
    Action2015
        Assembly Version: 1.0.0.0
        Win32 Version: 1.0.0.0
        CodeBase: file:///M:/OUTILS%20SUIVI/Action2015/Action2015.exe
    ----------------------------------------
    Microsoft.VisualBasic
        Assembly Version: 10.0.0.0
        Win32 Version: 10.0.30319.1 built by: RTMRel
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/Microsoft.VisualBasic/v4.0_10.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualBasic.dll
    ----------------------------------------
    System
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1026 built by: RTMGDR
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
    ----------------------------------------
    System.Core
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 built by: RTMRel
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Core/v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll
    ----------------------------------------
    System.Windows.Forms
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1032 built by: RTMGDR
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
    ----------------------------------------
    System.Drawing
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1001 built by: RTMGDR
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
    ----------------------------------------
    System.Runtime.Remoting
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1030 (RTMGDR.030319-1000)
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Runtime.Remoting/v4.0_4.0.0.0__b77a5c561934e089/System.Runtime.Remoting.dll
    ----------------------------------------
    System.Data.SQLite
        Assembly Version: 1.0.98.0
        Win32 Version: 1.0.98.0
        CodeBase: file:///M:/OUTILS%20SUIVI/Action2015/System.Data.SQLite.DLL
    ----------------------------------------
    System.Data
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_64/System.Data/v4.0_4.0.0.0__b77a5c561934e089/System.Data.dll
    ----------------------------------------
    System.Transactions
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_64/System.Transactions/v4.0_4.0.0.0__b77a5c561934e089/System.Transactions.dll
    ----------------------------------------
    System.Xml
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1026 built by: RTMGDR
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
    ----------------------------------------
    System.Data.DataSetExtensions
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 built by: RTMRel
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Data.DataSetExtensions/v4.0_4.0.0.0__b77a5c561934e089/System.Data.DataSetExtensions.dll
    ----------------------------------------
    System.Configuration
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1015 (RTMGDR.030319-1000)
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
    ----------------------------------------
    System.EnterpriseServices
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_64/System.EnterpriseServices/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.EnterpriseServices.dll
    ----------------------------------------
    System.Numerics
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 built by: RTMRel
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Numerics/v4.0_4.0.0.0__b77a5c561934e089/System.Numerics.dll
    ----------------------------------------
     
    ************** JIT Debugging **************
    To enable just-in-time (JIT) debugging, the .config file for this
    application or computer (machine.config) must have the
    jitDebugging value set in the system.windows.forms section.
    The application must also be compiled with debugging
    enabled.
     
    For example:
     
    <configuration>
        <system.windows.forms jitDebugging="true" />
    </configuration>
     
    When JIT debugging is enabled, any unhandled exception
    will be sent to the JIT debugger registered on the computer
    rather than be handled by this dialog box.
    Une idée ?

  6. #6
    Inactif  

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Janvier 2012
    Messages
    4 903
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 68
    Localisation : Canada

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Finance

    Informations forums :
    Inscription : Janvier 2012
    Messages : 4 903
    Billets dans le blog
    36
    Par défaut
    Bonjour,

    Il y a cela dans l'aide de VBA-Excel 2010. Je ne serais pas surpris qu'il y ait l'équivalent pour Excel 2013. Entre autres, il y a eu des modifications à l'Objet Range. Et une cellulle, c'est un objet Range. Tu vas devoir étudier un peu.

    Nom : ModèleObjetXL.jpg
Affichages : 3401
Taille : 183,0 Ko

    Sinon tu peux essayer un autre code:

    https://code.msdn.microsoft.com/site...xt=VB.NET&ac=5

  7. #7
    Membre averti
    Homme Profil pro
    Inscrit en
    Octobre 2012
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2012
    Messages : 15
    Par défaut
    Merci clementmarcotte pour les liens !

    Je vais regarder ça de plus près et je vous tiens au courant ..

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

Discussions similaires

  1. Export de données DataGridview Vers Excel
    Par Le gris dans le forum C#
    Réponses: 3
    Dernier message: 28/06/2012, 10h38
  2. Exporter le contenu d'un DataGridView vers Excel
    Par David Fouejio dans le forum Windows Forms
    Réponses: 7
    Dernier message: 31/05/2010, 10h50
  3. Datagridview vers excel
    Par urbanspike dans le forum VB.NET
    Réponses: 2
    Dernier message: 24/06/2009, 10h03
  4. Problème d'export de datagridview vers excel
    Par holdboy dans le forum C#
    Réponses: 2
    Dernier message: 15/06/2009, 21h54
  5. Exporter une dataGridView vers Excel
    Par drayif dans le forum Windows Forms
    Réponses: 2
    Dernier message: 02/08/2007, 17h45

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