从DataGridView写入Excel

Imports System.IO

 

Public Class Form1

 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        ExportDataGridViewToExcel(DataGridView1)

    End Sub

 

    Public Sub ExportDataGridViewToExcel(ByVal dataGridview1 As DataGridView)

        Dim saveFileDialog As SaveFileDialog = New SaveFileDialog

        saveFileDialog.Filter = "Execl files (*.xls)|*.xls"

        saveFileDialog.FilterIndex = 0

        saveFileDialog.RestoreDirectory = True

        saveFileDialog.CreatePrompt = True

        saveFileDialog.Title = "导出Excel"

        saveFileDialog.ShowDialog()

        Dim myStream As Stream

        myStream = saveFileDialog.OpenFile

        Dim sw As StreamWriter = New StreamWriter(myStream, System.Text.Encoding.Unicode)

        Dim str As String = ""

        Try

            Dim i As Integer = 0

            While i < dataGridview1.ColumnCount

                If i > 0 Then

                    str += "" & Microsoft.VisualBasic.Chr(9) & ""

                End If

                str += dataGridview1.Columns(i).HeaderText

                i = i + 1

            End While

            sw.WriteLine(str)

            Dim j As Integer = 0

            While j < dataGridview1.Rows.Count

                Dim tempStr As String = ""

                Dim k As Integer = 0

                While k < dataGridview1.Columns.Count

                    If k > 0 Then

                        tempStr += "" & Microsoft.VisualBasic.Chr(9) & ""

                    End If

                    tempStr += dataGridview1.Rows(j).Cells(k).Value.ToString

                    k = k + 1

                End While

                sw.WriteLine(tempStr)

                j = j + 1

            End While

 

            sw.Close()

            myStream.Close()

            MessageBox.Show("导出成功")

        Catch e As Exception

            MessageBox.Show(e.ToString & " 发生错误!")

        Finally

            sw.Close()

            myStream.Close()

        End Try

    End Sub

 

End Class

 

你可能感兴趣的:(从DataGridView写入Excel)