-3

我想从我的本地 PC 下载一个 excel 文件格式,所以我写了我的代码如下

protected void btnDownloadExcelTemp_Click(object sender, EventArgs e)
{
    try
    {
        string strFileFormat = System.Configuration.ConfigurationManager.AppSettings["FormateFilePath"].ToString();
        string strFilePath = HttpContext.Current.Server.MapPath(strFileFormat + "/CMP_TEMPLATES.xlsx");
        HttpResponse response = HttpContext.Current.Response;
        response.Clear();
        response.AppendHeader("content-disposition", "attachment; filename=" + "CMP_TEMPLATES.xlsx");
        response.ContentType = "application/octet-stream";
        response.WriteFile(strFilePath);
        response.Flush();
        response.End();
    }
    catch (Exception)
    {            
        throw;
    }
}

并且strFileFormat<add key="FormateFilePath" value="D:/Name/CMP/CMP Excel Template"/>

因此,在下载时出现错误

'D:/Name/CMP/CMP Excel Template/CMP_TEMPLATES.xlsx' 是物理路径,但应为虚拟路径。

我不知道它期待什么路径。请建议

4

1 回答 1

1

首先阅读文档:https ://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx 。

MapPath根据相对路径或虚拟路径生成物理路径,因此给它一个物理路径是没有意义的。您已经有了物理路径,因此您应该能够完全跳过该步骤。

protected void btnDownloadExcelTemp_Click(object sender, EventArgs e)
{
    try
    {
        string strFileFormat = System.Configuration.ConfigurationManager.AppSettings["FormateFilePath"].ToString();
        string strFilePath = strFileFormat + "/CMP_TEMPLATES.xlsx";
        HttpResponse response = HttpContext.Current.Response;
        response.Clear();
        response.AppendHeader("content-disposition", "attachment; filename=" + "CMP_TEMPLATES.xlsx");
        response.ContentType = "application/octet-stream";
        response.WriteFile(strFilePath);
        response.Flush();
        response.End();
    }
    catch (Exception)
    {            
        throw;
    }
}
于 2018-06-22T06:25:10.637 回答