如何将offcie文档(.doc、.xls、.ppt)转换成mht文档(代码篇)

这段代码展示了如何使用C#通过`Microsoft.HtmlTrans`库将Office文档(.doc、.xls、.ppt)转换成MHT格式。程序首先通过远程对象获取IHtmlTrLoadBalancer,然后利用IHtmlTrLauncher执行转换任务,读取输入文件内容,通过CHICreateHtml方法创建HTML,最后将HTML和附件合并为MHTML。

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

using System;
using Microsoft.HtmlTrans;
using System.Text;
using System.IO;
using System.Collections;

namespace OfficeDocConvertMHTML
{
   public class Conversion
   {
     // 字符串的编码
     protected static Encoding encoding = Encoding.Default;
     // 用于创建IHtmlTrLoadBalancerremoting对象的url
     protected static string strServiceUrl = "http://localhost:8093/HtmlTrLoadBalancer";
     public static void ConvertMHT(string inputfile, string outputfile)
     {
       // 通过url(strServiceUrl)获取一个IHtmlTrLoadBalancerremoting对象
       IHtmlTrLoadBalancer htmlTrLoadBalancer =
          (IHtmlTrLoadBalancer)System.Activator.GetObject(
          typeof(IHtmlTrLoadBalancer),strServiceUrl);
       // 用输入文件名(inputfile)作为一个任务的任务标示(strTask)
       string strTask = inputfile;

       // 根据任务标示(strTask)新建一个任务并获取任务的url(strLauncherUri)
       string strLauncherUri = htmlTrLoadBalancer.StrGetLauncher(strTask);

       // 通过任务的url(strLauncherUri)获取一个IHtmlTrLauncherremoting对象(htmlTrLauncher),
       // 并用这个对象来执行该任务
       IHtmlTrLauncher htmlTrLauncher =
          (IHtmlTrLauncher)System.Activator.GetObject(typeof(IHtmlTrLauncher),strLauncherUri);

       // 接下来是把输入文件(inputfile)的内容读入一个byte数组(bFile)
       byte[] bFile = null;
       FileStream fsInputMht = null;
       BinaryReader bwInputMht = null;
       try
       {
          fsInputMht = new FileStream(inputfile, FileMode.Open);
          bwInputMht = new BinaryReader(fsInputMht, encoding);
          bFile = new byte[fsInputMht.Length];
          for(long i = 0; i < bFile.LongLength; i++)
            bFile[i] = bwInputMht.ReadByte();
          bwInputMht.Close();
          fsInputMht.Close();

       }
       catch(Exception ex)
       {
          bwInputMht.Close();
          fsInputMht.Close();
          throw ex;
       }

       //CHICreateHtml 通过office文档创建HTML文件及其附件
       //CHICreateHtml(
       //string strLauncherUri,         任务的url
        //byte[] rgbFile,             office 文档的二进制内容
       //Microsoft.HtmlTrans.BrowserType bt, 使用浏览类型,该参数是一个枚举类型
       //string strReqFile,           office 文档的路径/url
       //string strTaskName,           任务标示名,HTML转换服务器根据其跟踪该请求
       //int timeout,                 转换超时时间,如果网络状况较差,建议值设大点
       //bool fReturnFileBits          是否返回二进制内容,分别保存在CreateHtmlInforgbMainFile属性和rgrgbThicketFiles属性中
       //);
       CreateHtmlInfo chi = htmlTrLauncher.CHICreateHtml(strLauncherUri, bFile,
          BrowserType.BT_IE4, inputfile, strTask, 120, true);

       //
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值