2014-01-21 6 views
0

Итак, у меня есть код, который экспортирует gridview в файл excel в Visual Basic.Экспорт GridView в 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, чтобы они соответствовали им. Благодарю.

+0

Возможно, с 'xlSheet.Cells.AutoFit()' как только рабочий лист заполнен. Или только в соответствующем диапазоне: 'xlSheet.Range (xlSheet.Cells (1, 1), xlSheet.Cells (DataGridView1.RowCount - 1, DataGridView1.ColumnCount - 1)). AutoFit()' – HLG13

+0

Я был избиение головок людей на стене - не используйте Interop для Office, если вам нужно только создать файл. Используйте OleDb.Ace и работайте с Excel так же, как с базой данных, человек. –

+0

HLG - Я поставил код перед тем, как сохранить файл, и я получил эту ошибку. «Ошибка метода автоопределения класса диапазона» T.S - Не могли бы вы привести пример изменения моего кода в формат OleDb.Ace? – Zingo

ответ

0

ОК, я добавил xlSheet.Columns.AutoFit() прямо перед Dim sFileName As String = Replace (dlgSave.FileName, .xlsx "," xlx ") И это сработало.

Смежные вопросы