利用poi开源jar包操作Excel时删除行内容与直接删除行的区别

一般情况下,删除行时会面临两种情况:删除行内容但保留行位置、整行删除(删除后下方单元格上移)。对应的删除方法分别是:

void removeRow(Row row)//Remove a row from this sheet. All cells contained in the row are removed as well
public void shiftRows(int startRow,int endRow,int n)//Shifts rows between startRow and endRow n number of rows. If you use a negative number, it will shift rows up. Code ensures that rows don't wrap around.

示例代码:

以下代码是使用removeRow()方法删除行内容但保留行位置。代码从d: est.xls中的第一个sheet中删除了第一行。需要注意的是,改变是需要在workbook.write之后才生效的。

[java] view plain copy
 
  1. import org.apache.poi.hssf.usermodel.*;  
  2. import java.io.*;  
  3. public class testTools{  
  4.      public static void main(String[] args){  
  5.         try {  
  6.             FileInputStream is = new FileInputStream("d://test.xls");  
  7.             HSSFWorkbook workbook = new HSSFWorkbook(is);  
  8.             HSSFSheet sheet = workbook.getSheetAt(0);  
  9.             HSSFRow row = sheet.getRow(0);  
  10.             sheet.removeRow(row);  
  11.             FileOutputStream os = new FileOutputStream("d://test.xls");  
  12.             workbook.write(os);  
  13.             is.close();  
  14.             os.close();  
  15.         } catch (Exception e) {   
  16.             e.printStackTrace();  
  17.         }  
  18.      }  
  19. }  



以下代码是使用shiftRow实现删除整行的效果。同样,也是需要在进行workbook.write后才会生效。

[java] view plain copy
 
  1. import org.apache.poi.hssf.usermodel.*;  
  2. import java.io.*;  
  3. public class testTools{  
  4.      public static void main(String[] args){  
  5.         try {  
  6.             FileInputStream is = new FileInputStream("d://test.xls");  
  7.             HSSFWorkbook workbook = new HSSFWorkbook(is);  
  8.             HSSFSheet sheet = workbook.getSheetAt(0);  
  9.             sheet.shiftRows(1, 4, -1);//删除第一行到第四行,然后使下方单元格上移  
  10.             FileOutputStream os = new FileOutputStream("d://test.xls");  
  11.             workbook.write(os);  
  12.             is.close();  
  13.             os.close();  
  14.         } catch (Exception e) {   
  15.             e.printStackTrace();  
  16.         }  
  17.      }  
  18. }  

自己写的一个包装好了的删除excel行的方法(利用shiftRows上移来删除行):

[java] view plain copy
 
    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(HSSFSheet sheet, int rowIndex) {  
    7.     int lastRowNum=sheet.getLastRowNum();  
    8.     if(rowIndex>=0&&rowIndex<lastRowNum)  
    9.         sheet.shiftRows(rowIndex+1,lastRowNum,-1);//将行号为rowIndex+1一直到行号为lastRowNum的单元格全部上移一行,以便删除rowIndex行  
    10.     if(rowIndex==lastRowNum){  
    11.         HSSFRow removingRow=sheet.getRow(rowIndex);  
    12.         if(removingRow!=null)  
    13.             sheet.removeRow(removingRow);  
    14.     }  
    15. }  
原文地址:https://www.cnblogs.com/telwanggs/p/5783816.html