vb.net从DataGridView复制到Excel.代码实现,解决中文乱码问题 (转载+亲自实践)

DataGridView中存在中文的场合,如果仅仅是直接粘贴Excel的话,会出现乱码,这时候最可靠的是选择性粘贴

网上大部分的说法是:选择性粘贴-->文本

但是本人测试过程中发现,有时候仅仅是文本还不够,依然有可能出现乱码的场合,最保险的就是:选择性粘贴-->Unicode 文本

以下程序是转载内容,我只是将其中的选择性粘贴内容修改为Unicode 文本

同时,程序中的killexcel() 杀掉程序创建的Excel进程方法非常好!!!值得学习

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim filepath As String = Application.StartupPath & "/" & Now.ToFileTimeUtc & ".xls"
            Dim objexcel As New Excel.Application()
            Dim objbook As Excel.Workbook = objexcel.Workbooks.Add()
            objbook.SaveAs(filepath)

            '设置复制模式为:连同行头和表头一起复制
            Me.DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
            '如果不需要复制行头,就把它隐藏掉
            Me.DataGridView1.RowHeadersVisible = False
            '选中DataGridView1的所有内容
            Me.DataGridView1.SelectAll()
            '判断DataGridView1中是否有选中单元格(与上面好像有点矛盾,自行处理)
            If Me.DataGridView1.GetCellCount(DataGridViewElementStates.Selected) > 0 Then
                Clipboard.SetDataObject(Me.DataGridView1.GetClipboardContent())
            End If
             '直接在Excel中粘贴
            'objexcel.ActiveSheet.paste()
            '為防止亂碼。使用選擇性粘貼
            '下面這一行,相當于在Excel中點擊右鍵->選擇性粘貼->文本
            'objexcel.ActiveSheet.PasteSpecial(Format:="文本", Link:=False, DisplayAsIcon:=False)

            '修改为选择性粘贴--> Unicode 文本

             objexcel.ActiveSheet.PasteSpecial(Format:="Unicode 文本", Link:=False, DisplayAsIcon:=False)
            '选中Excel所有单元格
            objexcel.Cells.Select()
            '不自动换行
            objexcel.Selection.WrapText = False
            '自动调整列宽
            objexcel.Columns.AutoFit()
            '储存
            objbook.Save()
            '退出
            objbook.Close()
            objexcel.Quit()
            objbook = Nothing
            objexcel = Nothing
            killexcel()
            '提示打开文件
            If MessageBox.Show("档案储存在:" & filepath & ",你要打开吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) = Windows.Forms.DialogResult.Yes Then
                Process.Start(filepath)
            End If
        Catch ex As Exception
            killexcel()
            MsgBox(ex.Message)
        End Try
    End Sub

    '杀掉程序创建的Excel进程
    Private Sub killexcel()
        Try
            For Each proc As Process In Process.GetProcessesByName("EXCEL")
                If proc IsNot Nothing AndAlso proc.MainWindowTitle = "" Then
                    proc.Kill()
                End If
            Next
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

你可能感兴趣的:(exception,String,Excel,each,button,VB.NET)