Search code examples
vb.netnpoi

With the use of NPOI, how to draw chart axis in excel?


NPOI version 2.2.1

The following is the sample code to generate excel with line chart, but there is no axis when the chart was generated.

The property (IsVisible) of bottomAxis is true already, but still cannot see it.

My question is how to make those axis visible?

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

    Dim wb As IWorkbook = New XSSFWorkbook()
    Dim ws As ISheet = wb.createSheet("linechart")
    Dim NUM_OF_ROWS = 3
    Dim NUM_OF_COLUMNS = 10


    For rowIndex As Integer = 0 To NUM_OF_ROWS
        Dim row = ws.CreateRow(rowIndex + 1)
        For colIndex As Integer = 0 To NUM_OF_COLUMNS
            Dim cell = ws.GetRow(rowIndex + 1).CreateCell(colIndex)
            cell.setCellValue(colIndex * (rowIndex + 1))
        Next

    Next
    Dim drawing = ws.createDrawingPatriarch()
    Dim anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15)
    Dim chart As IChart = drawing.createChart(anchor)
    Dim legend = chart.getOrCreateLegend()

    Dim dataFactory = chart.ChartDataFactory
    Dim chartAxisFactory = chart.ChartAxisFactory

    Dim lineChartData = dataFactory.createLineChartData(Of Double, Double)()
    Dim bottomAxis = chartAxisFactory.createCategoryAxis(NPOI.SS.UserModel.Charts.AxisPosition.BOTTOM)
    Dim leftAxis = chartAxisFactory.createValueAxis(NPOI.SS.UserModel.Charts.AxisPosition.RIGHT)


    Dim xs = NPOI.SS.UserModel.charts.DataSources.fromNumericCellRange(ws, New NPOI.SS.Util.CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1))
    Dim ys1 = NPOI.SS.UserModel.charts.DataSources.fromNumericCellRange(ws, New NPOI.SS.Util.CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1))
    Dim ys2 = NPOI.SS.UserModel.charts.DataSources.fromNumericCellRange(ws, New NPOI.SS.Util.CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1))


    lineChartData.addSeries(xs, ys1)
    lineChartData.addSeries(xs, ys2)

    chart.plot(lineChartData, bottomAxis, leftAxis)

    Dim file As FileStream = New FileStream("D:/feed//Xiaohongshu/" & "test" & ".xlsx", FileMode.Create)
    wb.Write(file)
    file.Close()


End Sub

Solution

  • This may be a bug for NPOI 2.2.1 We need to set IsVisible to False when deafult is True

    bottomAxis.IsVisible = False
    leftAxis.IsVisible = False