JSF - 使用POI移动工作表后,在Excel工作表的顶部插入一行

时间:2014-04-07 12:04:59

标签: apache-poi export-to-excel

我正在使用代码将行从第0行移到第4行。

但我的问题是,我需要在第0行插入一个标题。 我怎么能这样做?

这是我的代码

  HSSFWorkbook wb = (HSSFWorkbook) document;
            HSSFSheet sheet = wb.getSheetAt(0);
            wb.setSheetName(0, "report_lists"); // set sheet name
             sheet.shiftRows(0, sheet.getLastRowNum(), 4); //shifitng happens here.
//In the generated excel sheet I have four empty rows.But i need to enter some header in the top 4 rows NOT IN THE SHIFTED ROWS.


    //Now, I am getting the first row.
        HSSFRow firstrow= sheet.getRow(0);
        firstrow.getcell(0).setcellvalue("Actual"); 
        //I am assingning the value in for the cell 
        //but here is where I am getting NULL POINTER Exception while running the code



                HSSFRow header = sheet.getRow(4);
                HSSFCellStyle cellStyle = wb.createCellStyle();
                cellStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
                cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

                HSSFFont fontHeader = (HSSFFont) wb.createFont();
                fontHeader.setFontName("Calibri");
                cellStyle.setFont(fontHeader);
                for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
                    HSSFCell cell = header.getCell(i);
                    cell.setCellStyle(cellStyle);

                }
            }

1 个答案:

答案 0 :(得分:3)

而不是

HSSFRow firstrow= sheet.getRow(0);
firstrow.getcell(0).setcellvalue("Actual");

你应该使用

HSSFRow firstrow= sheet.getRow(0); // or sheet.createRow(0) if you didn't have row at 0(null pointer here)
firstrow.createCell(0).setcellvalue("Actual");