在Java中使用apache poi创建excel文件时出现空指针异常rowHeading.getCell(i).setCellStyle(stylerowHeading);

时间:2016-05-04 11:02:57

标签: java excel apache-poi

我正在浏览POI Excel教程。 当我执行下面的代码时,我得到NullPointer异常。 Plz建议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();
        }
    }

}

1 个答案:

答案 0 :(得分:0)

对于for循环的第一次迭代,您调用getCell(0),但不创建编号为0的单元格。第一个是rowHeading.createCell(1)