Wednesday 13 July 2011

Paste Excel Data Into DataGrid in VB.net


How to paste excel clipboard data in datagrid:

Private Sub PasteClipboard()

        Dim s As String
        Try

      
            s = Clipboard.GetText()
            Dim i, ii As Integer

            Dim tArr() As String = s.Split(ControlChars.NewLine)
            Dim arT() As String
            Dim cc, iRow, iCol As Integer

            iRow = DataGridView1.SelectedCells(0).RowIndex
            iCol = DataGridView1.SelectedCells(0).ColumnIndex
            For i = 0 To tArr.Length - 1
                If tArr(i) <> "" Then
                    arT = tArr(i).Split(vbTab)
                    cc = iCol
                    For ii = 0 To arT.Length - 1
                       If cc > DataGridView1.ColumnCount - 1 Then Exit For
                       If iRow > DataGridView1.Rows.Count - 1 Then Exit Sub
                        With DataGridView1.Item(cc, iRow)
                            .Value = arT(ii).TrimStart

                        End With
                        cc = cc + 1
                    Next
                    iRow = iRow + 1
                End If

            Next

        Catch ex As Exception
            MsgBox("Please redo Copy and Click on cell")
        End Try
    End Sub

Just change the value of DataGridView1 to the objectname of your DataGrid. This can paste rows and columns.

7 comments:

  1. excelente muy buen aporte... Gracias

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. no hay problema por favor siga

    ReplyDelete
  4. cool I will try it right now! If someone is interested in a workshop with a video about this issue you can take a look on http://www.excel-aid.com/the-excel-clipboard.html

    ReplyDelete
  5. My pleasure. Did you use this code on your clip ?
    Please give credit within your site. Thanks

    ReplyDelete
  6. Thanks a lot... It really helped me out.. Kudos.. \m/

    ReplyDelete