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

时间:2011-05-24 09:08:51

标签: .net vb.net excel grid

简单代码:

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

1 个答案:

答案 0 :(得分:1)

我假设网格是指数据网格视图?我认为您无法将数据绑定到excel。我前段时间写过这篇文章,将datagridview导出为ex​​cel:

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)