C#在Word中插入Html内容

3 篇文章 0 订阅
1 篇文章 0 订阅

同事遇到一个难题,就是在现有的Word模板中插入HTML内容,无论是HTML->Rtf,再插入Word,还是将HTML另存为xx.Doc然后用InsertFile插入都不是很好,格式会发生意外。因为HTML有两种,一种是纯网页标记,还有一种是doc->html,中间有很多微软的样式。

研究了一下C#操作Word的方法后,又Google一下怎么在指定书签位置插入内容的方法,后面就是核心的操作问题了。
思路是:
1.在文本框中输入html内容;
2.将html内容转换到WebBrowser上显示;
3.将WebBrowser上的内容复制到剪贴板;
4.打开Word模板,找到指定的书签,然后插入剪贴板内容。

还是利用以前VB的经验,先在Word中创建一个宏,然后复制和粘贴内容,然后查看宏代码:

Sub 宏1()
'
' 宏1 宏
'
'
    Selection.PasteAndFormat (wdFormatOriginalFormatting)
End Sub


关键代码有了,就是PasteAndFormat,参数也可以知道了,是wdFormatOriginalFormatting类型。
然后创建一个C#工程:

object docFileName = Application.StartupPath + "\\Sample.docx";
object missing = Type.Missing;

/// <summary>
/// 将html内容显示到WebBrowser上
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tsbtnConvert_Click(object sender, EventArgs e) {
    wbControl.DocumentText = txtText.Text;
    while (wbControl.DocumentText != txtText.Text) {
        Application.DoEvents();
    }

    OpenDocument();
}

/// <summary>
/// 打开Word模板,并插入内容
/// </summary>
private void OpenDocument() {
    wd.Application docApp = new wd.Application();
    //打开Word文件
    docApp.Documents.Open(ref docFileName,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing);
    //显示文件
    docApp.Visible = true;

    //书签名
    object bkObj = "content_1";
    if (docApp.ActiveDocument.Bookmarks.Exists("content_1")) {
        docApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
        //选中WebBrowser上内容,并复制到剪贴板
        wbControl.Document.ExecCommand("SelectAll", false, null);
        wbControl.Document.ExecCommand("Copy", false, null);
        //粘贴剪贴板内容
        docApp.Selection.PasteAndFormat(wd.WdRecoveryType.wdFormatOriginalFormatting);
    }

}


 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值