问题描述:

       

I try to load excel sheet which is having Macro using HSSF libraries. Once load the worksheet I am updating some data into rows and columns. It works fine.

When I remove a row from the spreadsheet using Apache POI Library the cell values in the row get clear and the row still exist with empty cells.

Anybody help me to delete rows from worksheet using Apache POI library.

HSSFWorkbook workbook = null;

InputputStream istream= new FileInputStream ("D://Review_Macros.xls");

POIFSFileSystem inputStream = new POIFSFileSystem(new BufferedInputStream(istream));
workbook = new HSSFWorkbook(istream);

HSSFRow row = null;
row= sheet.getRow(11);

//The below method removes only cell values not row.
sheet.removeRow(row);

FileOutputStream out = new FileOutputStream ("D:/Review_New.xls");
workbook.write(out);

解决方法:

       

 
  
  1. /**   
  2.      * Remove a row by its index   
  3.      * @param sheet a Excel sheet   
  4.      * @param rowIndex a 0 based index of removing row   
  5.      */   
  6.     public static void removeRow(Sheet sheet, int rowIndex) {   
  7.         int lastRowNum=sheet.getLastRowNum();   
  8.         if(rowIndex>=0&&rowIndex<lastRowNum){   
  9.             sheet.shiftRows(rowIndex+1,lastRowNum, -1);   
  10.         }   
  11.         if(rowIndex==lastRowNum){   
  12.             Row removingRow=sheet.getRow(rowIndex);   
  13.             if(removingRow!=null){   
  14.                 sheet.removeRow(removingRow);   
  15.             }   
  16.         }   
  17.     }