DataGridView Copy Paste (with style, background color, ...)

I have a C# Windows Form Application with a DataGridView.

Copy & Paste (ctrl-c after selecting the data in the datagrid and ctrl-v in Excel) is working almost fine.

The problem is that the style (such as background color) is not being pasted in Excel, only the cell values. Do I need to change a property somewhere on my datagridview or implement custom code?

Thanks,


AFAIK the only data grid property that affects clipboard behavior is the "ClipBoardCopyMode" and that pretty much is "use headers or not". Unless I am off base, if you want the formatting to go with it, you are going to have to put it in the clipboard yourself. But to be honest, as a user I wouldn't want the formatting. It drives me nuts when I copy things an then have to reformat them to match the format I'm currently using. I'd much rather paste in the data, and then if I want to format it as displayed, do that. If you are going to roll your own I'd suggest using the Excel Clipboard format so your user can "PasteSpecial" values if they want to. This might give you some ideas: http://www.codeguru.com/vb/gen/vb_misc/samples/article.php/c6393


I had the same problem, and used the Control.DrawToBitmap to add a bitmap to the ClipBoard. Using first a DataObject, populated with both the 'standard' clipboardcontent from the DataGridView, then adding the Bitmap, then pushing the DataObject to the Clipboard, the user is able to use 'paste special' functions and select between a bitmap or the plain text. Something like:

Dim data as New DataObject()  
Dim html As DataObject = DGV.GetClipboardContent()  
data.SetData(DataFormats.Html, html.GetData(DataFormats.Html))  
' create some rectangle, probably using DataGridView.Bounds  
Dim bitmap As New System.Drawing.Bitmap(rectangle.Width, rectangle.Height)  
DGV.DrawToBitmap(bitmap, rectangle)  
data.SetData(DataFormats.Bitmap, bitmap)  

There's also the possibility to create a RTF-output, but this is much more work as the RTF code is quite complex. However, there are some code examples to be found.

And I just stumbled across this example using XML-output for Excel and other formats.

链接地址: http://www.djcxy.com/p/62252.html

上一篇: datagridview复制到剪贴板异常

下一篇: DataGridView复制粘贴(带有样式,背景颜色...)