StreamReader.ReadToEnd excel下载
时间: 2024-02-01 11:14:59 浏览: 145
excel-streaming-reader
以下是通过 C# 中的 StreamReader 类读取 Excel 文件并将其下载的示例代码:
```csharp
string filePath = "C:\\path\\to\\file.xlsx";
string fileName = Path.GetFileName(filePath);
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (StreamReader streamReader = new StreamReader(fileStream))
{
// Read the entire file content into a memory stream
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(streamReader.ReadToEnd()));
// Send the memory stream to the client as a file attachment
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.OutputStream.Write(memoryStream.GetBuffer(), 0, memoryStream.GetBuffer().Length);
HttpContext.Current.Response.End();
}
}
```
此示例假定您已经将文件的完整路径存储在 `filePath` 变量中。在上面的代码中,我们使用 `StreamReader` 类读取文件的内容并将其存储在一个 `MemoryStream` 对象中。然后,我们将该 `MemoryStream` 对象发送到客户端作为文件附件。请注意,我们还需要设置正确的内容类型和文件名扩展名,以确保浏览器能够正确地处理下载文件。
阅读全文