简体   繁体   中英

Export datatable to Excel (VB window application)

So this is what i've tried. It successfully export but there's NO data. Empty excel. I guess i need to put some code to add row and column but i don't know how. I'm new in this.

      Try
        'Exporting to Excel.
        Dim folderPath As String = dtJelo.Rows(0)("jelly").ToString.Trim
        Dim filename As String = "JellyDetails" & current_yyyy & current_mon & ".xlsx"

        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim misValue As Object = System.Reflection.Missing.Value

        'addrow

        xlApp = New Excel.Application
        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkSheet = xlWorkBook.Sheets("sheet1")

        xlWorkSheet.SaveAs("C:\Users\spongebob\Desktop\" & filename & ".xlsx")

        xlWorkBook.Close()
        xlApp.Quit()

        releaseObject(xlApp)
        releaseObject(xlWorkBook)
        releaseObject(xlWorkSheet)

        MsgBox("Excel file created")


    Catch ex As Exception

    End Try

I am not exactly sure what you are trying to do here, but here is an example of creating an excel file and populating the cells with some data from an array.

Examples of arrays --> Arrays in Visual Basic

So here is the link to the code that you tried to use. Net-informations.com

You were missing the functions to return the year and day as a string to name the file. Also, you were missing the method releaseObject() from the original code that you used.

Test Code

Imports System
Imports System.Windows.Forms
Imports Microsoft.Office.Interop

Namespace WinFormTestApp
    Partial Public Class Form1
        Inherits Form

        Public Sub New()

            Call LoadData()

        End Sub

        Private Sub LoadData()
            Try

                'Exporting to Excel.
                'Dont know where this dtJelo comes from, so I just assigned a folder variable below.
                'Dim folderPath As String = dtJelo.Rows(0)("jelly").ToString.Trim
                Dim folderPath As String = "C:\temp\"
                Dim filename As String = "JellyDetails" & current_yyyy() & current_mon() & ".xlsx"

                Dim xlApp As Excel.Application = New Microsoft.Office.Interop.Excel.Application()
                Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add
                Dim xlWorkSheet As Excel.Worksheet = CType(xlWorkBook.Worksheets(1), Excel.Worksheet)

                'Create an array to populate Excel with
                Dim myArray(5) As String

                myArray(0) = "This is line number 1"
                myArray(1) = "This is line number 2"
                myArray(2) = "This is line number 3"
                myArray(3) = "This is line number 4"
                myArray(4) = "This is line number 5"
                myArray(5) = "This is line number 6"


                'This is where they are adding the code.
                xlWorkSheet.Cells(1, 1) = "Column Header Text"

                For xx As Integer = 0 To UBound(myArray)
                    'Add 2 to xx so that you do not overwrite the Column Header
                    xlWorkSheet.Cells(xx + 2, 1) = myArray(xx)
                Next

                xlWorkBook.SaveAs($"{folderPath}{filename}", Excel.XlFileFormat.xlWorkbookDefault)

                xlWorkBook.Close(True)
                xlApp.Quit()

                releaseObject(xlWorkSheet)
                releaseObject(xlWorkBook)
                releaseObject(xlApp)

                'MsgBox("Excel file created")
                MessageBox.Show($"Excel file created , you can find the file at {folderPath}{filename}")

            Catch ex As Exception

            End Try
        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

        Private Function current_mon() As String
            Try
                Return String.Format(Now.Month.ToString, "00")
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Private Function current_yyyy() As String
            Try
                Return Now.Year.ToString
            Catch ex As Exception
                Return Nothing
            End Try
        End Function
    End Class
End Namespace

Their Code

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim xlApp As Excel.Application = New Microsoft.Office.Interop.Excel.Application()

        If xlApp Is Nothing Then
            MessageBox.Show("Excel is not properly installed!!")
            Return
        End If


        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim misValue As Object = System.Reflection.Missing.Value

        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkSheet = xlWorkBook.Sheets("sheet1")
        xlWorkSheet.Cells(1, 1) = "Sheet 1 content"

        xlWorkBook.SaveAs("d:\csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, _
         Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue)
        xlWorkBook.Close(True, misValue, misValue)
        xlApp.Quit()

        releaseObject(xlWorkSheet)
        releaseObject(xlWorkBook)
        releaseObject(xlApp)

        MessageBox.Show("Excel file created, you can find the file d:\csharp-Excel.xls")
    End Sub

    'YOU WERE MISSING THIS FUNCTION IN YOUR EXAMPLE
    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

Here I propose for your addrow only, you can change range "A1" to other range:

    'addrow (you can create function for this, with datatable parameter and range parameter to begin)
    Dim IncludeLabel As Boolean = True
    For xx = 0 To dtJelo.Rows.Count - 1
        For yy = 0 To dtJelo.Columns.Count - 1
            If IncludeLabel = True Then
               If xx = 0 Then 
                  xlWorkSheet.range("a1").Offset(xx,yy).value=dtJelo.Columns(yy).ColumnName 
               End If
               xlWorkSheet.range("a1").Offset(xx+1,yy).value=dtJelo.Rows(xx)(yy) 
            Else
               xlWorkSheet.range("a1").Offset(xx,yy).value=dtJelo.Rows(xx)(yy) 
            End If
        Next
    Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM