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 as DataFormats.UnicodeText
or DataFormats.Text
but this gave me the output "#NAME?
" where I should see "-Infinity
" (because excel automatically inserts a "=
" before the minus in "-Infinity
" due to the standard cell format).
When I format the cells to "Text
" before pasting, excel does not automatically insert an "=
" before the "-Infinity
". By the way, I do not need to do any calculations with the double values in excel, so a text-format would be alright for me.
So my question is how to copy data to clipboard and paste it into excel while setting the cell format to "text".
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
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 clipboardThe 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
Thanks for the info. After some more searching, I found that you can use the .Net clipboard class, but you can't pass a String to SetData(). This works for me: