winform下word文件转.mht

本文介绍了一种将Word文档转换为单文件网页.mht格式的方法,以便在WebBrowser控件中更好地显示文档内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    做项目时有用webBrowser控件显示word文件的需要,但是比较惭愧,没有找到很舒心的方法,于是转而把word文件转换成单文件网页文件.mht来显示。p.s.:webBrowser控件宽度设置成750px比较能还原word文档的显示效果。

using System;
using System.Reflection;
using System.Text;
using System.IO;
using System.Collections;
using Microsoft.Office.Interop.Word;
public class Word2mht
{
    /// <summary>
    /// 提取文件绝对路径的文件名部分,并把文件名后缀换成.mht
    /// </summary>
    /// <param name="Directory"></param>
    /// <returns></returns>
    static public string GetMhtName(string Directory)
    {
        int pathLength = Directory.LastIndexOf(Path.DirectorySeparatorChar);
        string tmp = Directory.Substring(pathLength + 1);
        int dot = tmp.LastIndexOf('.');
        return DateTime.Today+tmp.Substring(0, dot)+".mht";
    }

    /// <summary> 
    /// word转成mht 
    /// </summary> 
    /// <param name="wordFileName"></param> 
    static public string WordToMht(string wordDirectory, string saveFileName)
    {
        Application word = new Application();
        Type wordType = word.GetType();
        Documents wordDocs = word.Documents;
        //打开Word文件 
        Type docsType = wordDocs.GetType();
        Document doc = (Document)docsType.InvokeMember(
            "Open",
            BindingFlags.InvokeMethod,
            null,
            wordDocs,
            new Object[]
            { 
                (object)(wordDirectory),
                true,
                true
            }
            );
        //转换格式,另存为 
        Type docType = doc.GetType();
        docType.InvokeMember(
            "SaveAs",
            BindingFlags.InvokeMethod,
            null,
            doc,
            new object[]
            {
                (object)saveFileName,
                WdSaveFormat.wdFormatWebArchive
            }
            );
        docType.InvokeMember("Close", BindingFlags.InvokeMethod, null, doc, null);
        //退出Word
        wordType.InvokeMember("Quit", BindingFlags.InvokeMethod, null, word, null);
        return saveFileName;
    } 
}
也看得出来吧,用了office的接口,没装office是没法用的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值