• ASP.NET实现word,PPT,Excel文件转换成html文件的通用方法
  • 阿汤哥 发表于 2016/2/20 12:16:00 | 分类标签: asp.net 生成html ppt格式
  • 以下是封装的一个ASP.NET实现office文件转化成html文件的通用方法,非常实用,喜欢的朋友可以收藏了。 
    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
    }
  • 请您注意

    ·自觉遵守:爱国、守法、自律、真实、文明的原则

    ·尊重网上道德,遵守《全国人大常委会关于维护互联网安全的决定》及中华人民共和国其他各项有关法律法规

    ·严禁发表危害国家安全,破坏民族团结、国家宗教政策和社会稳定,含侮辱、诽谤、教唆、淫秽等内容的作品

    ·承担一切因您的行为而直接或间接导致的民事或刑事法律责任

    ·您在编程中国社区新闻评论发表的作品,本网站有权在网站内保留、转载、引用或者删除

    ·参与本评论即表明您已经阅读并接受上述条款

  • 感谢本文作者
  • 作者头像
  • 昵称:阿汤哥
  • 加入时间:2013/5/15 0:00:00
  • TA的签名
  • 这家伙很懒,虾米都没写
  • +进入TA的空间
  • 以下内容也很赞哦
分享按钮