简体   繁体   English

从网址下载.xls文件

[英]Download .xls file from a url

I'm trying to download an xls file from a url: http://www.site.com/ff/excel/file.aspx?deven=0 我正在尝试从网址下载xls文件: http : //www.site.com/ff/excel/file.aspx? deven =0

I'm using this code but when the download is complete the file is not properly downloaded. 我正在使用此代码,但是下载完成后,文件没有正确下载。 How can I download this file correctly? 如何正确下载此文件?

string remoteFilename="http://www.site.com/ff/excel/file.aspx?deven=0";
string localFilename = "D:\\1\\1.xls";
Stream remoteStream = null;
Stream localStream = null;
WebResponse response = null;

try
{
    // Create a request for the specified remote file name
    WebRequest request = WebRequest.Create(remoteFilename);
    if (request != null)
    {
        // Send the request to the server and retrieve the
        // WebResponse object 
        response = request.GetResponse();
        response.ContentType = "application/vnd.ms-excel";

        if (response != null)
        {
            // Once the WebResponse object has been retrieved,
            // get the stream object associated with the response's data
            remoteStream = response.GetResponseStream();

            // Create the local file
            localStream = File.Create(localFilename);

            // Allocate a 1k buffer
            byte[] buffer = new byte[1024];
            int bytesRead;

            // Simple do/while loop to read from stream until
            // no bytes are returned
            do
            {
                // Read data (up to 1k) from the stream
                bytesRead = remoteStream.Read(buffer, 0, buffer.Length);

                // Write the data to the local file
                localStream.Write(buffer, 0, bytesRead);

                // Increment total bytes processed

            } while (bytesRead > 0);
        }
    }
}
catch (Exception e)
{
    MessageBox.Show(e.Message);
}
finally
{
    // Close the response and streams objects here 
    // to make sure they're closed even if an exception
    // is thrown at some point
    if (response != null) response.Close();
    if (remoteStream != null) remoteStream.Close();
    if (localStream != null) localStream.Close();
}
MessageBox.Show("file downl");

Use WebClient , it's much simpler: 使用WebClient ,它要简单得多:

using (WebClient webClient = new WebClient())
{
    webClient.DownloadFile(remoteFileName, localFilename);
}

if(File.Exists(localFilename))
    MessageBox.Show("File Downloaded");

Try flushing with localStream.Flush() AFTER your do {} while() , you might also want to wrap with a using statement. 尝试在do {} while() localStream.Flush()之后使用localStream.Flush()刷新,您可能还希望using语句进行包装。

For example: 例如:

// Create the local file
using (localStream = File.Create(localFilename)) {
    // Allocate a 1k buffer
   byte[] buffer = new byte[1024];
   int bytesRead;

   // Simple do/while loop to read from stream until
   // no bytes are returned
   do {
       // Read data (up to 1k) from the stream
       bytesRead = remoteStream.Read(buffer, 0, buffer.Length);

        // Write the data to the local file
        localStream.Write(buffer, 0, bytesRead);

        // Increment total bytes processed
    } while (bytesRead > 0);

    localStream.Flush();
}

This is how I download Excel files using a FilePathResult. 这就是我使用FilePathResult下载Excel文件的方式。

public FilePathResult DownloadFile(int ID)
{
    var log = _db.Logs.FirstOrDefault(x => x.LogID == ID);

    //Download the spreadsheet
    string fileName = string.Format("{0}.xlsx", ID);
    string path = _directory + "\\" + fileName;
    return File(path, "application/vnd.ms-excel", string.Format("{0}.xlsx", log.ReportTitle));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM