我正在使用ExcelLibrary enter link description here,因为我不想安装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
答案 0 :(得分:5)
您应该使用File(...)的Stream重载。您编写的代码似乎只返回文件的前4096个字节,即您复制到缓冲区的数量。您应该直接使用流。
Dim stream As New System.IO.MemoryStream
workbook.SaveToStream(stream)
stream.Position = 0
Return File(stream, "application/vnd.ms-excel", "mytestfile.xls")
答案 1 :(得分:0)
好。我想出了解决方案,我认为这个问题是excel文件的大小,但我不确定。所以我找到了这个“解决方案”:当我创建我的工作簿时,我填充第一个工作表的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