16,549
社区成员
发帖
与我相关
我的任务
分享
Private Sub CopyExcelToGrid()
If datagridview.CurrentCell Is Nothing Then
Return
End If
Dim insertRowIndex As Integer = datagridview.CurrentCell.RowIndex
'从剪贴板中取得格式本文数据
Dim pasteText As String = Clipboard.GetText()
If String.IsNullOrEmpty(pasteText) Then
Return
End If
pasteText = pasteText.Replace(" ", " ")
pasteText = pasteText.Replace(" "C, " "C)
pasteText.TrimEnd(New Char() {" "C})
Dim lines As String() = pasteText.Split(" "C)
Dim isHeader As Boolean = True
For Each line As String In lines
If isHeader Then
isHeader = False
Continue For
End If
Dim vals As String() = line.Split(" "C)
If vals.Length - 1 <> datagridview.ColumnCount Then
Throw New ApplicationException("列数错误")
End If
Dim row As DataGridViewRow = datagridview.Rows(insertRowIndex)
row.HeaderCell.Value = vals(0)
For i As Integer = 0 To row.Cells.Count - 1
row.Cells(i).Value = vals(i + 1)
Next
insertRowIndex += 1
Next
Dim iData As IDataObject = Clipboard.GetDataObject()
If iData.GetDataPresent(DataFormats.Text) Then
Dim str As String = DirectCast(iData.GetData(DataFormats.Text), [String])
End If
End Sub