粘贴excel信息

粘贴excel信息

Function pasteExcel(ByVal DGV As DataGridView)

        Try    ' 当前单元格是否选择的判断

            If DGV.CurrentCell Is Nothing Then

                Return (0)

            End If

            If DGV.Rows.Count = 1 Then

                DGV.Rows.Add("", "")

                DGV.CurrentCell = DGV.Item(0, 0)

            End If

            Dim insertRowIndex As Integer = DGV.CurrentCell.RowIndex

            ' 获取剪切板的内容,并按行分割

            Dim pasteText As String = Clipboard.GetText()

            If String.IsNullOrEmpty(pasteText) Then

                Return (0)

            End If

            pasteText = pasteText.Replace(vbCrLf, vbLf)

            pasteText = pasteText.Replace(vbCr, vbLf)

            pasteText.TrimEnd(New Char() {vbLf})

            Dim lines As String() = pasteText.Split(vbLf)

            Dim cell As String()

            ReDim Preserve lines(lines.Length - 2) '防止粘贴后出现空白

            For i As Integer = 0 To lines.Length - 1

                cell = lines(i).Split(ControlChars.Tab)

                For o = 0 To cell.Length - 1

                    If DGV.CurrentCell.ColumnIndex + o > DGV.Columns.Count - 1 Then DGV.Columns.Add("", "")

                    If DGV.CurrentCell.RowIndex + i > DGV.Rows.Count - 2 Then DGV.Rows.Add("", "")

                    If DGV.CurrentCell.ColumnIndex + o > 4 Then
                        Continue For '跳过循环
                    End If

                    DGV.Item(DGV.CurrentCell.ColumnIndex + o, DGV.CurrentCell.RowIndex + i).Value = cell(o)
                    If String.IsNullOrEmpty(cell(o)) = False Then
                        DGV.Item(4, DGV.CurrentCell.RowIndex + i).Value = "方正版"
                    End If
                Next
            Next

            'If DGV.CurrentCell.ColumnIndex = 0 Then

            '    Dim rtn& = MsgBox("检测到此次粘贴的目标位置处于表的第一行,是否需要将粘贴内容的第一行放入列标题?", MsgBoxStyle.YesNo, "提示!")

            '    If rtn = MsgBoxResult.Yes Then

            '        For i As Integer = 0 To DGV.Columns.Count - 1

            '            For o As Integer = 0 To DGV.Rows.Count - 2

            '                DGV.Rows.Item(o).HeaderCell.Value = Str(o + 1)

            '                If o = 0 Then DGV.Columns.Item(i).HeaderText = DGV.Item(i, o).Value

            '                DGV.Item(i, o).Value = DGV.Item(i, o + 1).Value

            '            Next

            '        Next

            '        DGV.Rows.RemoveAt(DGV.Rows.Count - 2)

            '    End If

            'End If

            Return (0)
        Catch ex As Exception

            MsgBox(ex.Message)

        End Try

        Return (0)

    End Function '粘贴excel信息

 

posted @ 2020-03-23 17:33  上帝视角  阅读(208)  评论(0编辑  收藏  举报