使用Aspose把office文件转换为Html文件及生成文件浏览乱码的解决

  • Post author:
  • Post category:其他


使用Aspose把office文件转换为Html 文件转换方法如下:

        /// <summary>
        /// office文件转换为Html
        /// </summary>
        /// <param name="extFileName">扩展名</param>
        /// <param name="sourceFile">源文件路径</param>
        /// <param name="desFile">目标文件</param>
        /// <returns></returns>
        public static string FileToHtmlFile(string extFileName, string sourceFile, string desFile)
        {
            if (string.IsNullOrEmpty(sourceFile))
            {
                return "0";//没有文件
            }

            switch (extFileName.ToUpper())
            {
                case "PPT":
                case "PPTX":
                    Aspose.Slides.Presentation ppt = new Aspose.Slides.Presentation(sourceFile);
                    ppt.Save(desFile, Aspose.Slides.Export.SaveFormat.Html);
                    break;
                case "DOC":
                case "DOCX":
                    Aspose.Words.Document doc = new Aspose.Words.Document(sourceFile);
                    doc.Save(desFile, Aspose.Words.SaveFormat.Html);
                    break;
                //case "XLS":
                    //case "XLSX":
                   //    break;
            }
            return "ok";
        }

PPT文件生成的html 会出现编码识别错误 导致浏览器网页乱码

解决方法如下,

                System.IO.StreamReader sr = new System.IO.StreamReader(strFilePath);
                string html = sr.ReadToEnd();
                sr.Close();
                System.IO.StreamWriter sw = new System.IO.StreamWriter(strFilePath, false);
                //System.IO.StreamWriter sw = new System.IO.StreamWriter(strFilePath, false, Encoding.UTF8);
                //特别重要:添加编码标志,解决浏览器识别错误
                html = html.Replace("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=9\">", "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=9\"><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
                //去除试用标志
                html = html.Replace("Evaluation only", "");
                html = html.Replace("Created with Aspose.Slides for .NET 2.0 14.8.1.0.", "");
                html = html.Replace("Copyright 2004-2014 Aspose Pty Ltd.", "");
                //html = html.Replace("Evaluation Only. Created with Aspose.Words. Copyright 2003-2014 Aspose Pty Ltd.", "");
                html = html.Replace("Evaluation Only. Created with Aspose.Words. Copyright 2003-2014 Aspose Pty Ltd.", "");
                html = html.Replace("This document was truncated here because it was created using Aspose.Words in Evaluation Mode.", "");
                // < meta http - equiv = "X-UA-Compatible" content = "IE=9" >< meta http - equiv = "Content-Type" content = "text/html; charset=utf-8" />
                sw.Write(html);
                sw.Close();



版权声明:本文为zhichao2001原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。