2

我正在使用 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

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

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

4

2 回答 2

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")
于 2014-07-30T22:39:06.913 回答
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
于 2014-07-31T14:51:09.700 回答