尝试使用NPOI填充Excel模板时出错

时间:2011-06-07 00:25:04

标签: asp.net vb.net excel npoi

使用NPOI并尝试遵循以下教程: http://www.zachhunter.com/2010/05/npoi-excel-template/, 我遇到了“未设置为对象实例的对象引用” 这一行的错误:

sheet.GetRow(1).GetCell(1).SetCellValue("some test value")

尝试使用此代码时:

Imports System.IO
Imports System.Web.Security
Imports NPOI.HSSF.UserModel
Imports NPOI.SS.UserModel
Imports NPOI.SS.Util
Imports NPOI.HSSF.Util
Imports NPOI.POIFS.FileSystem
Imports NPOI.HPSF



Partial Public Class NPOI_01
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    End Sub

    Public Shared Sub ExportDataTableToExcel(ByVal memoryStream As MemoryStream, ByVal fileName As String)
        Dim response As HttpResponse = HttpContext.Current.Response
        response.ContentType = "application/vnd.ms-excel"
        response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName))
        response.Clear()

        response.BinaryWrite(memoryStream.GetBuffer())
        response.[End]()
    End Sub

    Protected Sub DownloadReport_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim fs As New FileStream(Server.MapPath("spr_files\Book1.xls"), FileMode.Open, FileAccess.Read)

        Dim templateWorkbook As New HSSFWorkbook(fs, True)

        Dim sheet As HSSFSheet = templateWorkbook.GetSheet("Sheet1")

        sheet.GetRow(1).GetCell(1).SetCellValue("some test value")

        sheet.ForceFormulaRecalculation = True

        Dim ms As New MemoryStream()

        templateWorkbook.Write(ms)

        ExportDataTableToExcel(ms, "MyBook1Report.xls")
    End Sub


End Class

更新 我发现这种格式有效,如本博客文章http://www.leniel.net/2009/10/npoi-with-excel-table-and-dynamic-chart.html所示:

    Protected Sub DownloadReport_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim fs As New FileStream(Server.MapPath("spr_files\Book1.xls"), FileMode.Open, FileAccess.Read)

    Dim templateWorkbook As New HSSFWorkbook(fs, True)

    Dim sheet1 As HSSFSheet = templateWorkbook.GetSheet("Sheet1")
    Dim row1 As HSSFRow

    row1 = sheet1.CreateRow(1)
    row1.CreateCell(1).SetCellValue("some test value")
    'sheet1.GetRow(1).CreateCell(1).SetCellValue("some test value")

    sheet1.ForceFormulaRecalculation = True

    Dim ms As New MemoryStream()

    templateWorkbook.Write(ms)

    ExportDataTableToExcel(ms, "MyBook1Report.xls")
End Sub

然而问题仍然是开放的......为什么第一个例子中的代码不起作用? 您是否必须声明每一行新数据?当你有很多时会发生什么 数据库数据行?

1 个答案:

答案 0 :(得分:3)

在您的示例中,第一个使用“sheet.GetRow(1)”来抓取工作表中的现有行。第二个使用“sheet1.CreateRow(1)”,它在工作表中创建一个新行。从未使用/初始化的行不存在,并且在使用“CreateRow”创建之前无法访问。

为了证明这一点,您可以制作一行1的工作表,并在一个单元格中放置一个值。您可以使用GetRow(1)来获取行,然后尝试在不存在的行上使用GetRow(10)。您将得到该对象不存在,因为尚未创建该行。