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...