我在将一个html表从我的C#winforms应用程序拖到外部应用程序(Outlook电子邮件消息)并将其呈现为表而不是该表的纯文本版本时遇到问题。我知道当你在剪贴板中复制/粘贴时,你必须把表放在CF_HTML format中,但这似乎没有帮助拖动表。有谁知道我错过了什么?
答案 0 :(得分:7)
ObjectListView支持将行从ListView复制并拖动到其他应用程序,包括文本和HTML版本。要做到这一点,它会做这样的事情:
DataObject dataObject = new DataObject();
this.CreateTextFormats(dataObject);
Clipboard.SetDataObject(dataObject);
要进行拖放操作,代码几乎相同:
DataObject dataObject = new DataObject();
this.CreateTextFormats(dataObject);
DragDropEffects effect = this.DoDragDrop(dataObject, DragDropEffects.All);
CreateTextFormats()并不复杂:
public void CreateTextFormats(DataObject do) {
string textVersion;
string htmlVersion;
// Do the work of making the tab-separated text version and the HTML code
do.SetData(textVersion);
do.SetText(ConvertToHtmlFragment(htmlVersion), TextDataFormat.Html);
}
正确地获取HTML格式需要更长的时间:
/// <summary>
/// Convert the fragment of HTML into the Clipboards HTML format.
/// </summary>
/// <remarks>The HTML format is found here http://msdn2.microsoft.com/en-us/library/aa767917.aspx
/// </remarks>
/// <param name="fragment">The HTML to put onto the clipboard. It must be valid HTML!</param>
/// <returns>A string that can be put onto the clipboard and will be recognized as HTML</returns>
private string ConvertToHtmlFragment(string fragment) {
// Minimal implementation of HTML clipboard format
string source = "http://www.codeproject.com/KB/list/ObjectListView.aspx";
const String MARKER_BLOCK =
"Version:1.0\r\n" +
"StartHTML:{0,8}\r\n" +
"EndHTML:{1,8}\r\n" +
"StartFragment:{2,8}\r\n" +
"EndFragment:{3,8}\r\n" +
"StartSelection:{2,8}\r\n" +
"EndSelection:{3,8}\r\n" +
"SourceURL:{4}\r\n" +
"{5}";
int prefixLength = String.Format(MARKER_BLOCK, 0, 0, 0, 0, source, "").Length;
const String DEFAULT_HTML_BODY =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">" +
"<HTML><HEAD></HEAD><BODY><!--StartFragment-->{0}<!--EndFragment--></BODY></HTML>";
string html = String.Format(DEFAULT_HTML_BODY, fragment);
int startFragment = prefixLength + html.IndexOf(fragment);
int endFragment = startFragment + fragment.Length;
return String.Format(MARKER_BLOCK, prefixLength, prefixLength + html.Length, startFragment, endFragment, source, html);
}
答案 1 :(得分:0)
如果您不需要格式化,只需将其作为制表符分隔文本复制到剪贴板即可。这样它就会在Excel中粘贴成一个表格,并且可以推测大多数其他与表兼容的应用程序。