The solution to copying HTML to the clipboard

  • Thread starter Thread starter Tommy Carlier
  • Start date Start date
T

Tommy Carlier

I've seen a lot of messages from people who have trouble copying HTML
to the clipboard. I used to have the same problem, but I found a
solution. I needed to copy grid-data to Excel, so I decided to use the
HTML-format.
My solution (in C#) also solves an encoding-problem.

I hope that someone finds this useful.

using System;
using System.Text;
using System.Windows.Forms;

class Test
{
private void wfcCopyHTMLToClipBoard(string html)
{
Encoding enc = Encoding.UTF8;
string begin = "Version:0.9\r\nStartHTML:{0:000000}\r\nEndHTML:{1:000000}"
+ "\r\nStartFragment:{2:000000}\r\nEndFragment:{3:000000}\r\n";
string html_begin = "<html>\r\n<head>\r\n"
+ "<meta http-equiv=\"Content-Type\""
+ " content=\"text/html; charset=" + enc.WebName + "\">\r\n"
+ "<title>HTML clipboard</title>\r\n</head>\r\n<body>\r\n"
+ "<!--StartFragment-->";
string html_end = "<!--EndFragment-->\r\n</body>\r\n</html>\r\n";
int count_begin = lEncoding.GetByteCount(begin);
int count_html_begin = lEncoding.GetByteCount(html_begin);
int count_html = lEncoding.GetByteCount(html);
int count_html_end = lEncoding.GetByteCount(html_end);
string html_total = String.Format(
begin
, count_begin
, count_begin + count_html_begin + count_html + count_html_end
, count_begin + count_html_begin
, count_begin + count_html_begin + count_html
) + html_begin + html + html_end;
DataObject obj = new DataObject();
obj.SetData(DataFormats.Html, new System.IO.MemoryStream(
enc.GetBytes(html_total)));
Clipboard.SetDataObject(obj, true);
}
}
 
Isn't working for me

I tried this code and there seems to be a problem setting stuff in the clipboard as HTML.

If I change the DataFormat to something like text, it works, though it comes up mostly as Chinese text.
When I try to keep the DataFormat as Html, there is no error, but it just doesn't copy to the clipboard, though it seems to clear it.
I have even tried quitting the program after the copy to clipboard and then just pasting manually in Word, but when the DataFormat is Html, it doesn't paste.
 
Back
Top