如何在 vb.net 的 MVC 4 中创建并返回带有控制器的 Excel 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25047487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to I create and return an Excel File with a controller in MVC 4 in vb.net?
提问by EduardoUstarez
I am using ExcelLibrary enter link description herebecause I don't want to install Microsoft Office Excel (microsoft.interop.office.excel)
我正在使用 ExcelLibrary在此处输入链接描述,因为我不想安装 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
This code return an excel file, but when I try to open this file, It shows an error message (Excel found unreadable content in 'text.xls'. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes.) and it doesn't shows anything.
此代码返回一个 excel 文件,但是当我尝试打开此文件时,它显示一条错误消息(Excel 在 'text.xls' 中发现不可读的内容。是否要恢复此工作簿的内容?如果您信任此工作簿,单击是。)并且它不显示任何内容。
I working on Windows 8.1 (64 bits) and Microsoft Office 2013
我在 Windows 8.1(64 位)和 Microsoft Office 2013 上工作
采纳答案by EduardoUstarez
Well. I figured out solution, I think this problem is the size of the excel file, but I am not sure it. So I found this "solution": when I create my workbook, I fill 200 cells of the first sheet with null values to reach this size.
好。我想出了解决方案,我认为这个问题是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
回答by Michael Dunlap
You should use the Stream overload of File(...). The code you have written appears to only return the first 4096 bytes of the file, the amount you copied into the buffer. You should use the stream directly instead.
您应该使用 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")

