2014-01-21 149 views
0

所以我有一些代碼導出到Visual Basic中的Excel文件的gridview。導出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.Cells(1,1),xlSheet.Cells(DataGridView1.RowCount - 1,DataGridView1.ColumnCount - 1))。AutoFit()' – HLG13

+0

我一直在毆打牆上的人頭 - 如果您只需創建文件,請勿使用Office interop。就像使用數據庫man一樣使用OleDb.Ace並使用Excel。 –

+0

HLG - 我在保存文件之前將代碼放好,並且出現此錯誤。 「範圍類的自動調整方法失敗」 T.S - 你能否給我一個更改我的代碼爲OleDb.Ace格式的例子? – Zingo

回答

0

好吧,我在Dim sFileName As String = Replace(dlgSave.FileName,「.xlsx」,「xlx」)前添加了xlSheet.Columns.AutoFit()。