C#实现将PPT转换成HTML的方法
程序员文章站
2024-02-17 08:56:28
本文是一个c#的小程序,主要实现将ppt转换成html的功能,方法很多,此处与大家分享一下,希望能对大家的项目开发起到一定的借鉴作用。
主要功能代码如下:
us...
本文是一个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.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> /// 截取字符串左边指定长度 /// </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.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文件转换成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 }