In this case, the dataobject is a memory stream. Here are code snippets that allow you to get/set CSV values from/to the clipboard in a manner compatible with Excel.
[C#]
private void GetCSVFromClipBoard_Click(object sender, System.EventArgs e)
{
IDataObject o = Clipboard.GetDataObject();
if(o.GetDataPresent(DataFormats.CommaSeparatedValue))
{
StreamReader sr = new StreamReader((Stream) o.GetData(DataFormats.CommaSeparatedValue));
string s = sr.ReadToEnd();
sr.Close();
Console.WriteLine(s);
}
}
private void CopyCSVToClipBoard_Click(object sender, System.EventArgs e)
{
String csv = '1,2,3' + Environment.NewLine + '6,8,3';
byte[] blob = System.Text.Encoding.UTF8.GetBytes(csv);
MemoryStream s = new MemoryStream(blob);
DataObject data = new DataObject();
data.SetData(DataFormats.CommaSeparatedValue, s);
Clipboard.SetDataObject(data, true);
}
[VB.NET]
Private Sub GetCSVFromClipBoard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim o As IDataObject = Clipboard.GetDataObject()
If Not o Is Nothing Then
If (o.GetDataPresent(DataFormats.CommaSeparatedValue)) Then
Dim sr As New StreamReader(CType(o.GetData(DataFormats.CommaSeparatedValue), Stream))
Dim s As String = sr.ReadToEnd()
sr.Close()
Console.WriteLine(s)
End If
End If
End Sub ’GetCSVFromClipBoard_Click
Private Sub CopyCSVToClipBoard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim csv As String = '1,2,3' + Environment.NewLine + '6,8,3'
Dim blob As Byte() = System.Text.Encoding.UTF8.GetBytes(csv)
Dim s As New MemoryStream(blob)
Dim data As New DataObject()
data.SetData(DataFormats.CommaSeparatedValue, s)
Clipboard.SetDataObject(data, True)
End Sub ’CopyCSVToClipBoard_Click
Permalink