C# 導出Word報”無法打開Office open xml文件。因為文件內容有錯誤“ 解決方法


  • 郁悶了一天終於搞定這個問題了,出現這個問題時候文件其實內容還是可以打開的,就是出現以上的錯誤原因。經過最終分析確定了具體原因,是因為在Response下載文檔時候,最后需要結束

System.Web.HttpContext.Current.Response.End();否則默認為不完整下載狀態。反正我加上去后就不出現以上情況了。具體代碼如下:

      /// <summary>
        /// 下載文件
      /// </summary>
        public void LoadPaperTemplate(string mStrFileName)
        {
            FileStream fs = null;
            BinaryReader br = null;
            BinaryWriter brnew = null;
            try
            {
                //給內容賦值   
                string path = System.Web.HttpContext.Current.Server.MapPath("~/Template");
                string mStrFileRoot = string.Format("{0}\\{1}", path, mStrFileName);
                if (File.Exists(mStrFileRoot))
                {
                    fs = new System.IO.FileStream(mStrFileRoot, System.IO.FileMode.Open);
                    br = new BinaryReader((Stream)fs);
                    byte[] bytes = br.ReadBytes((Int32)fs.Length);
                    brnew = new BinaryWriter(fs);
                    brnew.Write(bytes, 0, bytes.Length);
                    System.Web.HttpContext.Current.Response.Clear();
                    System.Web.HttpContext.Current.Response.Buffer = true;
                    System.Web.HttpContext.Current.Response.Charset = "GB2312";
                    System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(mStrFileRoot.Substring(mStrFileRoot.LastIndexOf('\\') + 1)));
                    System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                    System.Web.HttpContext.Current.Response.ContentType = "application/ms-word";
                    System.Web.HttpContext.Current.Response.BinaryWrite(bytes);
                    System.Web.HttpContext.Current.Response.Flush();
                    System.Web.HttpContext.Current.Response.End();
                }
            }
            catch (Exception)
            {
                //throw;
            }
            finally
            {
                br.Close();
                brnew.Close();
                fs.Close();
            }
        }

 

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM