简体   繁体   中英

Export to Excel using Vb.net + Windows app

Simple code:

Private Sub ExportGridToExcel()
        Dim Excel As Object = CreateObject("Excel.Application")
        If Excel Is Nothing Then
            MsgBox("It appears that Excel is not installed on this machine. This operation requires MS Excel to be installed on this machine.", MsgBoxStyle.Critical)
            Return
        End If
        'Make Excel visible
        Excel.Visible = True
        'Initialize Excel Sheet
        With Excel
            .SheetsInNewWorkbook = 1
            .Workbooks.Add()
            .Worksheets(1).Select()

            'How to bind entire grid into excel without looping...

        End With
        Excel.Quit()
        System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)
        Excel = Nothing
        MsgBox("Export to Excel Complete", MsgBoxStyle.Information)
    End Sub

How to bind entire grid in to excel without looping..

I assume by the grid you mean a datagridview? I don't think you will be able to bind your data to excel. I wrote this some time ago to export a datagridview to excel:

private _dt as new Datatable

Dim strTempFile As String = My.Computer.FileSystem.GetTempFileName()
_dt = dgvResults.DataSource
Dim strLine As New StringBuilder("")

For c As Integer = 0 To _dt.Columns.Count - 1
    strLine.Append(_dt.Columns(c).ColumnName.ToString & ",")
Next
My.Computer.FileSystem.WriteAllText(strTempFile, strLine.ToString.TrimEnd(",") & vbCrLf, True)


For r As Integer = 0 To _dt.Rows.Count - 1
    strLine = New StringBuilder("")
    For c As Integer = 0 To _dt.Columns.Count - 1
        strLine.Append(_dt.Rows(r).Item(c).ToString & ",")
    Next
    My.Computer.FileSystem.WriteAllText(strTempFile, strLine.ToString.TrimEnd(",") & vbCrLf, True)
Next

Process.Start("excel", strTempFile)

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