0

I'm using VB and NPOI to write DATE data to an excel ROW.

I'm trying to use the following code to set the dataformat of the cell to "mm-dd-yy", but I keep getting an index out of range error when setting the cell.cellstyle.

There are a number of C examples of working code, but I'm trying this from VB.

        Dim CELLfont as HSSFFont = XLworkbook.CreateFont 
            CELLfont.FontName = "Arial"
            CELLfont.IsBold = True 

        Dim CELLstyle As HSSFCellStyle = XLworkbook.CreateCellStyle 

        With CELLstyle
                .BorderRight = BorderStyle.Double  
                .SetFont(CELLfont)  
                .DataFormat = XLworkbook.CreateDataFormat().GetFormat( "mm-dd-yy" )
        End With


        For C As Integer = 0 to DTforEXCELdata.Columns.Count - 1
             XLrow = XLsheet.CreateRow(XLrowCOUNTER)

             XLrow.CreateCell(C)
             XLrow.Cells(C).CellStyle = CELLstyle '**Error index out of range is here**
             XLrow.Cells(C).SetCellValue(DATEvalue)
        Next 

2 Answers2

0

You're applying the cellStyle to a negative number cell

For C As Integer = 0 to DTforEXCELdata.Columns.Count - 1

This is giving DTforEXCELdata.Columns.Count the value of 0

Step through the code that produces it and see if you can find out why

Badja
  • 857
  • 1
  • 8
  • 33
0

From the sample code given above, you create a new row instance each time you create new cell for each datatable columns.

You should create the row before iterating your columns to fill in your data for each cells in that new row.

   XLrow = XLsheet.CreateRow(XLrowCOUNTER) ' <-- to here

   For C As Integer = 0 to DTforEXCELdata.Columns.Count - 1
         'XLrow = XLsheet.CreateRow(XLrowCOUNTER) ' <-- move this code
         XLrow.CreateCell(C)
         XLrow.Cells(C).CellStyle = CELLstyle '**Error index out of range is here**
         XLrow.Cells(C).SetCellValue(DATEvalue)
   Next

The above will fix the error you experiencing.

ajakblackgoat
  • 2,119
  • 1
  • 15
  • 10