如何在vb.net中使用MVC 4中的控制器创build并返回Excel文件?

我正在使用ExcelLibrary 在这里input链接描述,因为我不想安装Microsoft Office Excel(microsoft.interop.office.excel)

Public Function ObtenerExcel() As ActionResult Dim workbook As New Workbook() Dim worksheet As New Worksheet("Sheet1") worksheet.Cells(5, 5) = New Cell(999999) worksheet.Cells(10, 10) = New Cell(12354) workbook.Worksheets.Add(worksheet) Dim stream As New System.IO.MemoryStream workbook.SaveToStream(stream) stream.Position = 0 Dim buffer(4096) As Byte stream.Read(buffer, 0, buffer.Length) Return File(buffer, "application/vnd.ms-excel", "mytestfile.xls") End Function 

此代码返回一个excel文件,但是当我尝试打开这个文件时,它显示一个错误消息(Excel在'text.xls'中发现了不可读的内容。你想恢复这个工作簿的内容吗?如果你相信此工作簿,单击是。),它不显示任何内容。

我在Windows 8.1(64位)和Microsoft Office 2013上工作

您应该使用File(…)的Stream重载。 您所编写的代码似乎只返回文件的前4096个字节,即您复制到缓冲区的数量。 您应该直接使用stream。

 Dim stream As New System.IO.MemoryStream workbook.SaveToStream(stream) stream.Position = 0 Return File(stream, "application/vnd.ms-excel", "mytestfile.xls") 

好。 我想出了解决scheme,我认为这个问题是Excel文件的大小,但我不确定。 所以我find了这个“解决scheme”:当我创build我的工作簿时,我用第一个工作表的200单元格填充空值达到这个大小。

 Public Function ObtenerExcel() As ActionResult Dim stream As New System.IO.MemoryStream Dim doc As CompoundDocument = CompoundDocument.Create(stream) Dim memStream As New MemoryStream Dim workbook As New Workbook() Dim worksheet As New Worksheet("Hoja") For Index As Integer = 0 To 200 worksheet.Cells(Index, 0) = New Cell(Nothing) Next workbook.Worksheets.Add(worksheet) workbook.SaveToStream(stream) stream.Position = 0 Return File(stream, "application/vnd.ms-excel", "mytestfile.xls") End Function