简体   繁体   English

使用 Vb.net + Windows 应用程序导出到 Excel

[英]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..如何将整个网格绑定到 excel 而不循环..

I assume by the grid you mean a datagridview?我假设网格是指datagridview? I don't think you will be able to bind your data to excel.我认为您无法将数据绑定到 excel。 I wrote this some time ago to export a datagridview to 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