0

I am going through POI Excel tutorial on you tube. when I executed following code I get NullPointer exception. Plz suggest the ans. Thanku.

package main;

import entities.*;
import dao.*;
import java.util.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import java.io.*;


public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try{
            ProductModel pmodel = new ProductModel();
            HSSFWorkbook workbook= new HSSFWorkbook();
            HSSFSheet sheet=workbook.createSheet("List Products");
            //create heading
            Row rowHeading = sheet.createRow(0);
            rowHeading.createCell(1).setCellValue("Id");
            rowHeading.createCell(2).setCellValue("Name");
            rowHeading.createCell(3).setCellValue("Creation Date");
            rowHeading.createCell(4).setCellValue("Price");
            rowHeading.createCell(5).setCellValue("Sub Total");

            for(int i=0;i<6;i++)
            {
                CellStyle stylerowHeading= workbook.createCellStyle();
                Font font = workbook.createFont();
                font.setBold(true);
                font.setFontName(HSSFFont.FONT_ARIAL);
                font.setFontHeightInPoints((short)11);
                stylerowHeading.setFont(font);
                stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);
                rowHeading.getCell(i).setCellStyle(stylerowHeading);

            }

            //save to excel
            FileOutputStream out =  
                    new FileOutputStream("D:\\AVIATE\\excel\\listproducts.xls");
            workbook.write(out);
            out.close();
            System.out.println("Excel written successfully........");

        }catch(Exception e){
            System.out.println("exception");
            e.printStackTrace();
        }
    }

}
Guillaume Barré
  • 4,168
  • 2
  • 27
  • 50

1 Answers1

0

For the first iteration of the for cycle, you call getCell(0) , but you do not create a cell with number 0. The first one is rowHeading.createCell(1).

user3719857
  • 1,083
  • 4
  • 16
  • 45