玩转C科技.NET

从学会做人开始认识这个世界!http://volnet.github.io

导航

关于EXCEL下载后无法打开的问题

image

通过流的下载的方式下载文件的需求很普遍,也基本不太会错,但最近用VPN(这套系统用的是网页反代的方式来实现),下载的Excel却无法打开,仔细检查后通过增加ContentType,修正了这个问题。代码分享如下:

byte[] bytes = System.IO.File.ReadAllBytes(path);
                    ms.Write(bytes, 0, bytes.Length);
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlPathEncode(displayFileName));
                    string contentType = GetContentType(path);
                    if (!string.IsNullOrEmpty(contentType))
                    {
                        Response.ContentType = contentType;
                    }
                    Response.BinaryWrite(ms.ToArray());
                    Response.End();

其中ContentType部分如下:

public const string ExcelContentType_97Or2003 = "application/vnd.ms-excel";
public const string ExcelContentType_2007 = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 

public string GetContentType(string path)
{
    string extension = Path.GetExtension(path).ToLower();
    if (extension.EndsWith("xlsx") || extension.EndsWith("xlsm"))
    {
        return ExcelContentType_2007;
    }
    else if (extension.EndsWith("xls"))
    {
        return ExcelContentType_97Or2003;
    }
    return string.Empty;
}

posted on 2011-08-04 12:54  volnet(可以叫我大V)  阅读(1762)  评论(0编辑  收藏  举报

使用Live Messenger联系我
关闭