簡體   English   中英

使用 Vb.net + Windows 應用程序導出到 Excel

[英]Export to Excel using Vb.net + Windows app

簡單代碼:

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

如何將整個網格綁定到 excel 而不循環..

我假設網格是指datagridview? 我認為您無法將數據綁定到 excel。 我前段時間寫了這個來將datagridview導出到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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM