从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

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值