将GridView导出到Excel

时间:2014-01-21 18:30:10

标签: vb.net excel visual-studio-2008 datagrid

所以我有一些代码将gridview导出到Visual Basic中的excel文件。

   Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
    ExportExcel()
End Sub

    Private Sub ExportExcel()
    'Create excel objects
    Dim xlApp As Microsoft.Office.Interop.Excel.Application
    Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
    Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
    Dim oValue As Object = System.Reflection.Missing.Value

    Dim sPath As String = String.Empty

    'cereate new object SaveFileDialog that will be use to save the file
    Dim dlgSave As New SaveFileDialog

    'Create a new instance of databale, this will server as container of data
    Dim dt As New DataTable

    'We need to set the default extension to xls so the SaveFileDialog will save the file
    'as excel file
    dlgSave.DefaultExt = "xls"

    'Set the filter for SaveFileDialog
    dlgSave.Filter = "Microsoft Excel|*.xls"

    'set the initial path, you may set a different path if you like
    dlgSave.InitialDirectory = Application.StartupPath

    'Export the data if the user click the ok button of SaveFileDialog
    If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then
        Try
            'Create a new instance of excel application
            xlApp = New Microsoft.Office.Interop.Excel.Application

            'Create an excel workbook
            xlBook = xlApp.Workbooks.Add(oValue)

            'Create an excel sheet named sheet1
            xlSheet = xlBook.Worksheets("sheet1")


            Dim xlRow As Long = 2
            Dim xlCol As Short = 1

            'To create a column for excel we need to loop through DataTable(dtStudentGrade)
            For k As Integer = 0 To DataGridView1.ColumnCount - 1

                'Get the column name and assigned it to excel sheet cells
                'to assign value to each cell we need to specify the row and column xlSheet.Cells(row, column)
                xlSheet.Cells(1, xlCol) = DataGridView1(k, 0).Value

                'Increment the xlCol so we can set another column
                xlCol += 1

            Next

            'reset the progressbar
            Me.ProgressBar1.Visible = True
            Me.ProgressBar1.Minimum = 0
            Me.ProgressBar1.Maximum = DataGridView1.Rows.Count

            'Loop through dtStudentGrade to get the value of each field in a row
            For i As Integer = 0 To DataGridView1.RowCount - 1
                'Reset xlCol's value to 1 
                xlCol = 1

                'Loop through dtStudentGrade and set the value of each excel sheet cells
                For k As Integer = 0 To DataGridView1.ColumnCount - 1

                    'Assign the value of each field to selected excel sheet cell
                    xlSheet.Cells(xlRow, xlCol) = DataGridView1(k, i).Value

                    'Increment the xlCol so we can set another the the value of another cell
                    xlCol += 1
                Next

                'Increment the xlCol
                xlRow += 1

                'Set the value of progressbar
                If Me.ProgressBar1.Maximum > Me.ProgressBar1.Value + 1 Then
                    Me.ProgressBar1.Value = Me.ProgressBar1.Value + 1
                End If

            Next

            'Set the filename and set the filename to xlx to save the file as excel 2003
            'You may remove the Replace function and save the file with xlsx(excel 2007) extension
            Dim sFileName As String = Replace(dlgSave.FileName, ".xlsx", "xlx")

            'save the file
            xlSheet.SaveAs(sFileName)

            'close the workbook
            xlBook.Close()

            'Quit the application using this code
            xlApp.Quit()

            'Release the objects used by excell application by calling our procedure releaseObject
            releaseObject(xlApp)
            releaseObject(xlBook)
            releaseObject(xlSheet)

            'Reset the progressbar
            Me.ProgressBar1.Value = 0
            Me.ProgressBar1.Visible = False

            'inform the user if successfull
            MsgBox("Data successfully exported.", MsgBoxStyle.Information, "PRMS/SOB Date Tagging")
        Catch
            MsgBox(ErrorToString)
        Finally

        End Try
    End If

End Sub

当我打开excel文件时,excel中的所有列都太短而无法显示所有信息而无需手动使其更宽。有没有办法对此进行编码以适应excel的列以匹配im导出?感谢。

1 个答案:

答案 0 :(得分:0)

好的,我在Dim sFileName As String = Replace(dlgSave.FileName,“。xlsx”,“xlx”)之前添加了xlSheet.Columns.AutoFit()并且它有效。

相关问题