In C# I need to copy data-grid rows to excel. Because some values in a row are doubles, \"-Infinity
\" values are possible.
I\'ve tried to copy the rows
Starting with a Raw Clipboard viewer you can see that copying
to the clipboard results in Excel throwing a large number of different formats to the clipboard.
Most of these aren't helpful, but some of them are internal to excel, meaning it will (almost) guarantee that the data will be the same as copied. If I were you I'd probably target XML SpreadSheet or if your feeling brave Biff12 which is also xml (but zipped). This will give you far more control over the paste than normal text.
As an example the above clip results in
1 |
2 |
Test |
-Infinity |
So looking a little deeper still... It seem's the .Net Clipboard class does some wierd and not so wonderful things when I tried to use Clipboard.SetData
to write the xml to the clipboard
The clipboard starts with a load of chaff. This of course results in Excel rejecting the clipboard contents.
To get around this I use the Windows API (user32) calls to work with the clipboard
[DllImport("user32.dll", SetLastError = true)]
static extern uint RegisterClipboardFormat(string lpszFormat);
[DllImport("user32.dll")]
static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem);
[DllImport("user32.dll", SetLastError = true)]
static extern bool CloseClipboard();
[DllImport("user32.dll", SetLastError = true)]
static extern bool OpenClipboard(IntPtr hWndNewOwner);
private static void XMLSpreadSheetToClipboard(String S)
{
var HGlob = Marshal.StringToHGlobalAnsi(S);
uint Format = RegisterClipboardFormat("XML SpreadSheet");
OpenClipboard(IntPtr.Zero);
SetClipboardData(Format, HGlob);
CloseClipboard();
Marshal.FreeHGlobal(HGlob);
}