Reading xls stream with GetResponseStream and Spre

2019-07-27 07:00发布

问题:

I want to read an xls from a server. I succeeded to download the file with the WebClient, but now I want to open it without saving the file.

        var request = WebRequest.Create(location);
        var response = request.GetResponse();
        var stream = response.GetResponseStream();
        var document = SpreadsheetDocument.Open(stream, false);
        if (stream != null) stream.Close();

My code stops on the SpreadsheetDocument.Open, it gives teh following error:

Cannot operate on stream that does not support seeking.

What am I doing wrong, why can't I open the document?

回答1:

You receive this error because the Open method of SpreadsheetDocument expects a seekable stream object. Your stream variable is an instance of NetworkStream and does not support seeking. You will have to copy the networkstream into a local stream (eg a MemoryStream) in order to use it in your code

var request = WebRequest.Create(location);
var response = request.GetResponse();

var memoryStream = new MemoryStream();
using (var networkStream = response.GetResponseStream())
{
    if (networkStream != null)
    {
        // Copy the network stream to an in-memory variable
        networkStream.CopyTo(memoryStream);
        // Move the position of the stream to the beginning
        memoryStream .Seek(0, SeekOrigin.Begin);
    }
}

var document = SpreadsheetDocument.Open(memoryStream , false);