无法将html格式的字符串复制到剪贴板

时间:2015-09-02 09:23:57

标签: c# html winforms office-interop

我正在尝试将html格式的字符串从我的数据库复制到word文档。我需要能够像子弹一样恢复格式。使用下面的代码,我得到一个异常

  

“指定的数据类型不可用。”

下面是要复制到剪贴板并写入word文档的代码。

DataObject clipDO = new DataObject();
clipDO.SetData(DataFormats.Html, HtmlClipboardData(temp));
Thread thread = new Thread(() => Clipboard.SetDataObject(clipDO, true));
thread.ApartmentState = ApartmentState.STA;
thread.Start();
thread.Join();
Microsoft.Office.Interop.Word.Paragraph oPara = wordApp.Selection.Paragraphs.Add(ref oMissing);
object pasteType = WdPasteDataType.wdPasteHTML;
oPara.Range.PasteSpecial(ref oMissing, ref oMissing, ref oMissing, ref oMissing, pasteType, ref oMissing, ref oMissing);

代码现在停止工作了。当它提前工作时,它不会将html复制到剪贴板。它会写入word doc,剪贴板的先前内容。 将标题添加到html字符串的帮助方法如下所示。

    private static string HtmlClipboardData(string html)
    {
        StringBuilder sb = new StringBuilder();
        Encoding encoding = Encoding.GetEncoding("utf-8");
        string Header = @"
        Version: 1.0
        StartHTML: {0:000000}
        EndHTML: {1:000000}
        StartFragment: {2:000000}
        EndFragment: {3:000000}
        ";
        string HtmlPrefix = @"
        !DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//TR""
        html
        head
        meta http-equiv=Content-Type content=""text/html; charset={0}""
        head
        body
        !--StartFragment--
        ";
        HtmlPrefix = string.Format(HtmlPrefix, encoding.WebName);

        string HtmlSuffix = @"
        <!--EndFragment-->
        </body>
        </html>
        ";

        // Get lengths of chunks
        int HeaderLength = encoding.GetByteCount(Header);
        HeaderLength -= 16; // extra formatting characters {0:000000}
        int PrefixLength = encoding.GetByteCount(HtmlPrefix);
        int HtmlLength = encoding.GetByteCount(html);
        int SuffixLength = encoding.GetByteCount(HtmlSuffix);

        // Determine locations of chunks
        int StartHtml = HeaderLength;
        int StartFragment = StartHtml + PrefixLength;
        int EndFragment = StartFragment + HtmlLength;
        int EndHtml = EndFragment + SuffixLength;

        // Build the data
        sb.AppendFormat(Header, StartHtml, EndHtml, StartFragment, EndFragment);
        sb.Append(HtmlPrefix);
        sb.Append(html);
        sb.Append(HtmlSuffix);
        return sb.ToString();
    }

问题是html字符串没有复制到剪贴板。当我在剪贴板中有一些特殊内容(比如从命令提示符复制的内容)时,PasteSpecial会将该数据粘贴到我的word文档中。

1 个答案:

答案 0 :(得分:0)

尝试使用DataFormats.Text。