程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#完成將PPT轉換成HTML的辦法

C#完成將PPT轉換成HTML的辦法

編輯:C#入門知識

C#完成將PPT轉換成HTML的辦法。本站提示廣大學習愛好者:(C#完成將PPT轉換成HTML的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成將PPT轉換成HTML的辦法正文


本文是一個C#的小法式,重要完成將ppt轉換成html的功效,辦法許多,此處與年夜家分享一下,願望能對年夜家的項目開辟起到必定的自創感化。

重要功效代碼以下:

using System;
 using System.Collections.Generic;
 using System.Text;
 using System.IO;
 using PPT = Microsoft.Office.Interop.PowerPoint;
 using System.Reflection;

namespace WritePptDemo
 {
   class Program
   {
     static void Main(string[] args)
     {
       string  path;     //文件途徑變量

       PPT.Application pptApp;   //Excel運用法式變量
        PPT.Presentation pptDoc;   //Excel文檔變量

       PPT.Presentation pptDoctmp;

      path  = @"C:\MyPPT.ppt";   //途徑
       pptApp =  new PPT.ApplicationClass();  //初始化

      //假如已存在,則刪除
       if  (File.Exists((string)path))
       {
          File.Delete((string)path);
       }

      //因為應用的是COM庫,是以有很多變量須要用Nothing取代
       Object  Nothing = Missing.Value;
       pptDoc =  pptApp.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);
        pptDoc.Slides.Add(1,  Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText);

       string text = "示例文本";

      foreach  (PPT.Slide slide in pptDoc.Slides)
       {
          foreach (PPT.Shape shape in slide.Shapes)
          {
            shape.TextFrame.TextRange.InsertAfter(text);
          }
       }

        //WdSaveFormat為Excel文檔的保留格局
        PPT.PpSaveAsFileType format = PPT.PpSaveAsFileType.ppSaveAsDefault;

      //將excelDoc文檔對象的內容保留為XLSX文檔 
        pptDoc.SaveAs(path, format, Microsoft.Office.Core.MsoTriState.msoFalse);

      //封閉excelDoc文檔對象 
        pptDoc.Close();

      //封閉excelApp組件對象 
        pptApp.Quit();

       Console.WriteLine(path + " 創立終了!");

       Console.ReadLine();


       string  pathHtml = @"c:\MyPPT.html";

       PPT.Application pa = new PPT.ApplicationClass();

       pptDoctmp = pa.Presentations.Open(path,  Microsoft.Office.Core.MsoTriState.msoTrue,  Microsoft.Office.Core.MsoTriState.msoFalse,  Microsoft.Office.Core.MsoTriState.msoFalse);
        PPT.PpSaveAsFileType formatTmp = PPT.PpSaveAsFileType.ppSaveAsHTML;
        pptDoctmp.SaveAs(pathHtml, formatTmp,  Microsoft.Office.Core.MsoTriState.msoFalse);
        pptDoctmp.Close();
       pa.Quit();
        Console.WriteLine(pathHtml + " 創立終了!");
     }
   }
 }
 

以上法式是應用C# 先創立一個ppt 文件並向外面寫入了文字,然後再把此ppt 轉換成html  ,關於下面法式須要解釋的其實就是

援用dll的成績, 在項目中添加援用,在com 組件當選擇 microsoft powerpoint 11.0 object   library ,而假如你的電腦沒有裝置 office 2003 是不會有這個的,而假如裝置的是office 2007 則是microsoft powerpoint 12.0 object   library。並且即便你援用勝利後,照樣會編譯欠亨過,是由於少裝置了 office   PIA  ,在裝置office 時,假如你是選擇的典范裝置是不會裝置這個的,由於這個只針對開辟人員才會用到。可以到網高低載一個 office PIA 裝置下就ok了
 
Office文件轉換成Html格局功效代碼以下:  

 using  Microsoft.Office.Core;
 using Microsoft.Office.Interop.PowerPoint;

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Web;
 using System.IO;
 using System.Text.RegularExpressions;
 using Nd.Webs;
 using Aspose.Cells;
 using Aspose.Words;
 using ND.CommonHelper;
 using Microsoft.Office.Interop.PowerPoint;
 using Microsoft.Office.Core;

namespace Api.Note.Base
 {
   #region Office文件轉換成Html格局
   class OfficeHtmlBo
   {
     #region InsertHeadHtml
     /// <summary>
     /// InsertHeadHtml
     /// </summary>
     /// <param  name="WordFilePath">InsertHeadHtml</param>
     private string  InsertHeadHtml(string strHtml, string realPath)
     {
       int index  = strHtml.IndexOf("<body");
       strHtml =  strHtml.Insert(index, "<div  style='height:60px;font-size:14px;margin:0px 0px  12px 0px;padding:14px 4px 12px 12px;line-height:24px;height:1%;'>以下是該文檔的HTML預覽後果。<br/><span>因為是網頁提取顯示word中的內容,有能夠部門顯示與源文檔中有差別,如想檢查更精確的信息,</span>您可以點擊 <a  style='color:6699FF;text-decoration:underline;'  href='/Lib/UdControls/Download.aspx?action=Download&appFormCode=" +  HttpContext.Current.Request.QueryString["appFormCode"].ToString() +  "&path=" +  HttpContext.Current.Request.QueryString["path"].ToString() +  "&encrypt=" + HttpContext.Current.Request.QueryString["encrypt"].ToString()  + "'><b>下載原始附件</b></a></div>");

      Regex  reg = new  Regex(@"(?<start><img[^>]+?src="")(?<src>[^""]+?)(?<end>""[^>]+?>)");
       strHtml =  reg.WordStr(strHtml, delegate(Match m)
       {
          return string.Format("{0}{1}{2}{3}",
            m.Groups["start"].Value,
            realPath,
            m.Groups["src"].Value,
            m.Groups["end"].Value
            );
       });

       return strHtml;
     }
     #endregion

    #region GetLeftStr
     /// <summary>
     /// 截取字符串右邊指定長度
     /// </summary>
     /// <param  name="str"></param>
     /// <param  name="length"></param>
     ///  <returns></returns>
     public string GetLeftStr(string  str, int length)
     {
       length =  length * 2;
       string  tempStr = "";
       int i = 0;
       foreach  (char c in str)
       {
          tempStr += c.ToString();
          if (((int)c >= 33) && ((int)c <= 126))
          {
            //字母和符號原樣保存 
            i += 1;
          }
          else
          {
            i += 2;
          }
          if (i >= length)
          {
            return tempStr;
          }
       }
       return  str;
     }

     #endregion

    #region 將Word文檔轉換成HTML格局
     /// <summary>
     /// 將Word文檔轉換成HTML格局
     /// </summary>
     /// <param  name="WordFilePath">Word文檔格局</param>
     private void WordToHtmlFile(string  WordFilePath)
     {
       try
       {
          // 指定原文件和目的文件
          string realPath = WordFilePath.Substring(0,  WordFilePath.LastIndexOf("/") + 1);
          WordFilePath = System.Web.HttpContext.Current.Server.MapPath(WordFilePath);
          object target = WordFilePath.Substring(0,  WordFilePath.LastIndexOf(".")) + ".html";
          //string realPath = WordFilePath.Substring(0,  WordFilePath.LastIndexOf(".")) + ".html";

         if (!File.Exists(target.ToString()))
          {
            Document doc = new Document(WordFilePath);
            doc.Save(target.ToString(), SaveFormat.Html);
          }
         StreamReader sr = new StreamReader(target.ToString(), Encoding.Default);
          string strHtml = sr.ReadToEnd();
         strHtml = InsertHeadHtml(strHtml, realPath);
          HttpContext.Current.Response.Write(strHtml);
         sr.Close();
       }
       catch  (Exception ex)
       {
          //記載異常
          LogEntry logEntry = new LogEntry();
          logEntry.Message = ex.Message;
          logEntry.Title = "---->將Word文檔轉換成HTML格局異常[WordToHtmlFile]";
          logEntry.TimeStamp = DateTime.Now;
          logEntry.LogEntryType = LogEntryType.Error;
          logEntry.LogCatalog = LogCatalog.ExceptionLog;
          logEntry.StackTrace = ex.StackTrace;
          LogPosition logPosition = LogPosition.FileLog;
          string positionParameter =  SysConfig.ToString(SysConfig.GetAppSetting("LogPath"));
          SysLogger.Write(logEntry, logPosition, positionParameter);
       }
     }
     #endregion

    #region 將Excel文件轉換成HTML格局
     /// <summary>
     /// 將Excel文件轉換成HTML格局
     /// </summary>
     /// <param  name="ExcelFilePath">Excel文件途徑</param>
     private void  ExcelToHtmlFile(string ExcelFilePath)
     {
       try
       {
          string realPath = ExcelFilePath.Substring(0,  ExcelFilePath.LastIndexOf("/") + 1);
          int index = ExcelFilePath.LastIndexOf("/");
          string fileName;
          if (ExcelFilePath.IndexOf(":") != -1)
          {
            fileName = ExcelFilePath.Split(new char[] { ':' })[0].ToString();
            fileName = GetLeftStr(fileName.Substring(0,  fileName.LastIndexOf(".")), 10) +  fileName.Substring(fileName.LastIndexOf("."));
            fileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8);
          }
          else
          {
            fileName = ExcelFilePath.Substring(index + 1, ExcelFilePath.Length - index -  1);
            fileName = GetLeftStr(fileName.Substring(0,  fileName.LastIndexOf(".")), 10) +  fileName.Substring(fileName.LastIndexOf("."));
            //編碼
            fileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8);
          }
          fileName = fileName.Substring(0, fileName.LastIndexOf("."));
          ExcelFilePath = System.Web.HttpContext.Current.Server.MapPath(ExcelFilePath);
          //目的html文件途徑
          object target = ExcelFilePath.Substring(0,  ExcelFilePath.LastIndexOf(".")) + ".html";
         string target2 = ExcelFilePath.Substring(0,  ExcelFilePath.LastIndexOf("\\")) + "\\" + fileName +  "_files\\sheet001.htm";
          if (!File.Exists(target.ToString()))
          {
            //為了保險,只讀方法翻開 
            //object readOnly = true;
            //// 指定另存為格局(html) 
            //object format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
           ////翻開Excel文件
            //oBook = excelApp.Workbooks.Open(ExcelFilePath, Unknown, readOnly,
            //  Unknown, Unknown, Unknown, Unknown, Unknown, Unknown,
            //  Unknown, Unknown, Unknown, Unknown, Unknown, Unknown);
           //// 轉換格局 
            //oBook.SaveAs(target, format, Unknown, Unknown, Unknown, Unknown,
            //    Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
            //   Unknown, Unknown, Unknown, Unknown, Unknown);

           Workbook wBook = new Workbook();
            wBook.Open(ExcelFilePath);
            wBook.Save(target.ToString(), FileFormatType.Html);
          }

         StreamReader sr = new StreamReader(target2.ToString(), Encoding.Default);
          string strHtml = sr.ReadToEnd();

         strHtml = InsertHeadHtml(strHtml, realPath);

         strHtml = strHtml.WordStr("window.location.replace", "");
          strHtml = strHtml.WordStr("filelist.xml", realPath + "/"  + fileName + "_files/filelist.xml");
          strHtml = strHtml.WordStr("stylesheet.css", realPath +  "/" + fileName + "_files/stylesheet.css");
          HttpContext.Current.Response.Write(strHtml);

         sr.Close();
       }
       catch  (Exception ex)
       {
          //記載異常
          LogEntry logEntry = new LogEntry();
          logEntry.Message = ex.Message;
          logEntry.Title = "---->將Excel文件轉換成HTML格局[ExcelToHtmlFile]";
          logEntry.TimeStamp = DateTime.Now;
          logEntry.LogEntryType = LogEntryType.Error;
          logEntry.LogCatalog = LogCatalog.ExceptionLog;
          logEntry.StackTrace = ex.StackTrace;
          LogPosition logPosition = LogPosition.FileLog;
          string positionParameter =  SysConfig.ToString(SysConfig.GetAppSetting("LogPath"));
          SysLogger.Write(logEntry, logPosition, positionParameter);
       }
     }
     #endregion

    #region 將PPT文件轉換成HTML格局
     /// <summary>
     /// 將PPT文件轉換成HTML格局
     /// </summary>
     /// <param  name="PptFilePath">PPT文件途徑</param>
     private void PptToHtmlFile(string  PptFilePath)
     {
        ApplicationClass ac = new ApplicationClass();
        Presentation pptFile = null;
       try
       {
          string realPath = PptFilePath.Substring(0,  PptFilePath.LastIndexOf(".")) + ".html";
          PptFilePath = System.Web.HttpContext.Current.Server.MapPath(PptFilePath);
          //取得html文件名
          object target = PptFilePath.Substring(0,  PptFilePath.LastIndexOf(".")) + ".html";

         if (!File.Exists(target.ToString()))
          {
            if (PptFilePath.Contains(".pptx"))
            {
              pptFile = ac.Presentations.Open2007(PptFilePath, MsoTriState.msoCTrue,  MsoTriState.msoCTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
              pptFile.SaveAs(target.ToString(), PpSaveAsFileType.ppSaveAsHTML,  MsoTriState.msoCTrue);
            }
            else if (PptFilePath.Contains(".ppt"))
            {
              pptFile = ac.Presentations.Open(PptFilePath, MsoTriState.msoCTrue,  MsoTriState.msoCTrue, MsoTriState.msoFalse);
              pptFile.SaveAs(target.ToString(), PpSaveAsFileType.ppSaveAsHTML,  MsoTriState.msoCTrue);
            }
          }
          //StreamReader sr = new StreamReader(target.ToString(), Encoding.Default);
          //string strHtml = sr.ReadToEnd();
          //Response.Write(strHtml);
          HttpContext.Current.Response.Redirect(realPath);
       }
       finally
       {
          if (pptFile != null)
          {
            pptFile.Close();
          }
          ac.Quit();
          GC.Collect();
       }
     }
     #endregion
   }
   #endregion
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved