zoukankan      html  css  js  c++  java
  • 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();
                }
            }
    

        

  • 相关阅读:
    A.4.2虚函数 virtual 和多态的实现
    A.51,集合类 ArrayList。2,对字符串的处理(String)
    A.4.1类的继承(implement)
    Android ExpandableListView的使用
    Android 使用SAX解析XML
    [转]Android 内存监测工具 DDMS > Heap .
    Android中 ExpandableList的使用2
    Android 横屏竖屏的切换
    Android 文件操作
    Android Preference的使用总结(很全很详细)以及SharedPreferences多个程序之间共享数据
  • 原文地址:https://www.cnblogs.com/BeyondWJsel/p/2494418.html
Copyright © 2011-2022 走看看