C#實(shí)現(xiàn)將PPT轉(zhuǎn)換成HTML的方法
本文是一個(gè)C#的小程序,主要實(shí)現(xiàn)將ppt轉(zhuǎn)換成html的功能,方法很多,此處與大家分享一下,希望能對(duì)大家的項(xiàng)目開(kāi)發(fā)起到一定的借鑒作用。
主要功能代碼如下:
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應(yīng)用程序變量 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庫(kù),因此有許多變量需要用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文檔對(duì)象的內(nèi)容保存為XLSX文檔 pptDoc.SaveAs(path, format, Microsoft.Office.Core.MsoTriState.msoFalse); //關(guān)閉excelDoc文檔對(duì)象 pptDoc.Close(); //關(guān)閉excelApp組件對(duì)象 pptApp.Quit(); Console.WriteLine(path + " 創(chuàng)建完畢!"); 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 + " 創(chuàng)建完畢!"); } } }
以上程序是使用C# 先創(chuàng)建一個(gè)ppt 文件并向里面寫(xiě)入了文字,然后再把此ppt 轉(zhuǎn)換成html ,對(duì)于上面程序需要說(shuō)明的其實(shí)就是
引用dll的問(wèn)題, 在項(xiàng)目中添加引用,在com 組件中選擇 microsoft powerpoint 11.0 object library ,而如果你的電腦沒(méi)有安裝 office 2003 是不會(huì)有這個(gè)的,而如果安裝的是office 2007 則是microsoft powerpoint 12.0 object library。而且即使你引用成功后,還是會(huì)編譯不通過(guò),是因?yàn)樯侔惭b了 office PIA ,在安裝office 時(shí),如果你是選擇的典型安裝是不會(huì)安裝這個(gè)的,因?yàn)檫@個(gè)只針對(duì)開(kāi)發(fā)人員才會(huì)用到??梢缘骄W(wǎng)上下載一個(gè) office PIA 安裝下就ok了
Office文件轉(zhuǎn)換成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文件轉(zhuǎn)換成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預(yù)覽效果。<br/><span>由于是網(wǎng)頁(yè)提取顯示word中的內(nèi)容,有可能部分顯示與源文檔中有差異,如想查看更準(zhǔn)確的信息,</span>您可以點(diǎn)擊 <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.Replace(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> /// 截取字符串左邊指定長(zhǎng)度 /// </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)) { //字母和符號(hào)原樣保留 i += 1; } else { i += 2; } if (i >= length) { return tempStr; } } return str; } #endregion #region 將Word文檔轉(zhuǎn)換成HTML格式 /// <summary> /// 將Word文檔轉(zhuǎn)換成HTML格式 /// </summary> /// <param name="WordFilePath">Word文檔格式</param> private void WordToHtmlFile(string WordFilePath) { try { // 指定原文件和目標(biāo)文件 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文檔轉(zhuǎn)換成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文件轉(zhuǎn)換成HTML格式 /// <summary> /// 將Excel文件轉(zhuǎn)換成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); //目標(biāo)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())) { //為了保險(xiǎn),只讀方式打開(kāi) //object readOnly = true; //// 指定另存為格式(html) //object format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml; ////打開(kāi)Excel文件 //oBook = excelApp.Workbooks.Open(ExcelFilePath, Unknown, readOnly, // Unknown, Unknown, Unknown, Unknown, Unknown, Unknown, // Unknown, Unknown, Unknown, Unknown, Unknown, Unknown); //// 轉(zhuǎn)換格式 //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.Replace("window.location.replace", ""); strHtml = strHtml.Replace("filelist.xml", realPath + "/" + fileName + "_files/filelist.xml"); strHtml = strHtml.Replace("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文件轉(zhuǎn)換成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文件轉(zhuǎn)換成HTML格式 /// <summary> /// 將PPT文件轉(zhuǎn)換成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 }
相關(guān)文章
C#實(shí)現(xiàn)順序隊(duì)列和鏈隊(duì)列的代碼實(shí)例
今天小編就為大家分享一篇關(guān)于C#實(shí)現(xiàn)順序隊(duì)列和鏈隊(duì)列的代碼實(shí)例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10C#執(zhí)行表達(dá)式樹(shù)(Expression Tree)的具體使用
本文將深入探討表達(dá)式樹(shù)的基本概念、創(chuàng)建方法、修改和刪除節(jié)點(diǎn)、查詢和遍歷技巧以及在C#中的應(yīng)用示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03C#使用Socket實(shí)現(xiàn)發(fā)送和接收?qǐng)D片的方法
這篇文章主要介紹了C#使用Socket實(shí)現(xiàn)發(fā)送和接收?qǐng)D片的方法,涉及C#操作socket發(fā)送與接收文件的使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-04-04