使用GetResponseStream和SpreadsheetDocument.Open读取xls流 [英] Reading xls stream with GetResponseStream and SpreadsheetDocument.Open
问题描述
我想从服务器读取xls.我已经使用WebClient成功下载了文件,但是现在我想不保存文件就将其打开.
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();
我的代码在SpreadsheetDocument.Open上停止,它给出以下错误:
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?
推荐答案
由于SpreadsheetDocument的Open方法需要 NetworkStream 的实例,并且不支持搜寻.您将必须将网络流复制到本地流(例如, MemoryStream),以便在您的代码中使用
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);
这篇关于使用GetResponseStream和SpreadsheetDocument.Open读取xls流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!