TransmitFile和WriteFile

时间:2013-12-17 11:57:50

标签: c# asp.net asp.net-mvc excel file

我使用TransmitFile和WriteFile编写Excel文件,但任何人都无法正常工作 我的代码是:

// Get the Physical Path of the file(test.doc)
        string filepath = newFilePath;

        // Create New instance of FileInfo class to get the properties of the file being downloaded
        FileInfo file = new FileInfo(filepath);

        // Checking if file exists
        if (file.Exists)
        {
            // Clear the content of the response
            HttpContext.Current.Response.ClearContent();

            // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
            HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name));


            // Add the file size into the response header
            HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());

            // Set the ContentType
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

            // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
            HttpContext.Current.Response.TransmitFile(file.FullName);



        }


        FileStream sourceFile = new FileStream(file.FullName, FileMode.Open);
        float FileSize;
        FileSize = sourceFile.Length;
        byte[] getContent = new byte[(int)FileSize];
        sourceFile.Read(getContent, 0, (int)sourceFile.Length);
        sourceFile.Close();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.AddHeader("Content-Length", getContent.Length.ToString());
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        HttpContext.Current.Response.BinaryWrite(getContent);

1 个答案:

答案 0 :(得分:0)

我会将其简化为:

public ActionResult ExcelDoc(string newFilePath)
{
    string filepath = newFilePath;

    // Create New instance of FileInfo class to get the properties of the file being downloaded
    FileInfo file = new FileInfo(filepath);

    // Checking if file exists
    if (file.Exists)
    {
        var fileBytes = System.IO.File.ReadAllBytes(filepath);
        Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name));
        return File(new MemoryStream(fileBytes), "application/vnd.ms-excel");
    }
    else
    {
        return Content("File does not exist");
    }
}