nieyangjie

把datagridview 里面的数据导出成excel的例子


Imports Microsoft.Office.Interop
Imports System.IO

Public Class Form1

   
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       
Try
           
With Me.SaveFileDialog1
                .Filter
= "Excel File(*.xls)|*.xls"
               
If .ShowDialog = Windows.Forms.DialogResult.OK Then
                   
Dim strFileName As String = .FileName
                   
Dim objDataTable As DataTable = New DataTable
                    objDataTable.Columns.Add(
"col1")
                    objDataTable.Columns.Add(
"col2")
                    objDataTable.Columns.Add(
"col3")
                    objDataTable.Rows.Add(
"1", "test1", "abc1")
                    objDataTable.Rows.Add(
"2", "test2", "abc2")
                    objDataTable.Rows.Add(
"3", "test3", "abc3")
                    ExportExcel(strFileName, objDataTable)
               
End If
           
End With
       
Catch ex As Exception
           
MsgBox(ex.Message)
       
End Try
   
End Sub

   
Private Sub ExportExcel(ByVal istrFileName As String, ByVal iobjData As DataTable)
       
Dim objXlsApp As Excel.Application = Nothing
       
Dim objXlsBook As Excel.Workbook = Nothing
       
Dim objXlsSheet As Excel.Worksheet = Nothing
       
Try
            objXlsApp
= New Excel.Application
            objXlsApp.Visible
= False
            objXlsApp.DisplayAlerts
= False
           
If File.Exists(istrFileName) Then
                File.Delete(istrFileName)
           
End If
            objXlsBook
= objXlsApp.Workbooks.Add()
            objXlsSheet
= objXlsBook.Sheets(1)
           
For intRow As Integer = 0 To iobjData.Rows.Count - 1
               
For intCol As Integer = 0 To iobjData.Columns.Count - 1
                    objXlsSheet.Cells(intRow
+ 1, intCol + 1) = iobjData.Rows(intRow)(intCol)
               
Next
           
Next
            objXlsBook.SaveAs(istrFileName)
       
Finally
            objXlsSheet
= Nothing

           
If objXlsBook IsNot Nothing Then
                objXlsBook.Close()
           
End If

           
If objXlsApp IsNot Nothing Then
                objXlsApp.Visible
= True
                objXlsApp.DisplayAlerts
= True
                objXlsApp.Quit()
           
End If
       
End Try
   
End Sub

End Class

posted on 2009-08-18 13:58  nieyangjie  阅读(436)  评论(0编辑  收藏  举报

导航