我正在使用WebApi导出excel文件,但是它引发了异常,我不知道为什么。我用Google搜索它,但没有找到任何解决方案。
项目:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>Error while copying content to a stream.</ExceptionMessage>
<ExceptionType>System.Net.Http.HttpRequestException</ExceptionType>
<StackTrace>
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at Microsoft.AspNet.WebApi.Extensions.Compression.Server.BaseServerCompressionHandler.<HandleCompression>d__17.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult() at Microsoft.AspNet.WebApi.Extensions.Compression.Server.BaseServerCompressionHandler.<SendAsync>d__15.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()
</StackTrace>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>Cannot access a closed Stream.</ExceptionMessage>
<ExceptionType>System.ObjectDisposedException</ExceptionType>
<StackTrace>
at System.IO.__Error.StreamIsClosed() at System.IO.MemoryStream.get_Position() at System.Net.Http.StreamToStreamCopy.StartAsync()
</StackTrace>
</InnerException>
</Error>
我的代码是:
[AllowAnonymous]
[HttpGet]
[Route("api/AddPatient/ExportToExcel")]
public HttpResponseMessage ExportToExcel()
{
try
{
MemoryStream dataStream = Utility.GetFile();
HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = "Test.xlsx";
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
return httpResponseMessage;
}
catch (Exception ex)
{
throw;
}
}
GetFile 功能如下,用于获取Excel内存流 注意:使用NPOI我正在创建Excel文件
public static MemoryStream GetFile()
{
MemoryStream stream =null;
XSSFWorkbook wb = new XSSFWorkbook();
ISheet sheet = wb.CreateSheet("Test");
var row = sheet.CreateRow(0);
var cell = row.CreateCell(0);
cell.SetCellValue("Test");
using ( stream = new MemoryStream())
{
wb.Write(stream);
}
return stream;
}
答案 0 :(得分:0)
在处理流对象时需要小心。
但是我认为您获取dataStream
的函数也是错误的。也许还有更多代码?
try
{
using(MemoryStream dataStream = Utility.GetFile())
{
// read from beginning
dataStream.Position = 0;
HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = "Test.xlsx";
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
return httpResponseMessage;
}
}
catch (Exception ex)
{
throw;
}
您的GetFile
无法使用using换行,这将关闭您的内存流对象。
// try this
public static MemoryStream GetFile()
{
MemoryStream stream = new MemoryStream();
// do your thing
XSSFWorkbook wb = new XSSFWorkbook();
ISheet sheet = wb.CreateSheet("Test");
var row = sheet.CreateRow(0);
var cell = row.CreateCell(0);
cell.SetCellValue("Test");
wb.Write(stream);
// reset position here
stream.Position = 0;
return stream;
}