2017-07-24 216 views
0

我想使用Apache-POI刪除最後10行。我試圖在網上找到解決方案,沒有運氣。 我的代碼:刪除最後一行Excel時出錯 - Apache POI

import java.io.*; 
import org.apache.poi.hssf.usermodel.HSSFRow; 
import org.apache.poi.sl.usermodel.Sheet; 
import org.apache.poi.xssf.usermodel.*; 


    public class Sample1 { 

     public static void main(String[] args)throws Exception 
     { 

      File file = new File("File.xlsx"); 
      FileInputStream fIP = new FileInputStream(file); 
      XSSFWorkbook wb = new XSSFWorkbook(fIP); 
      XSSFSheet sheet = wb.getSheetAt(1); 
      int lastRowNum = sheet.getLastRowNum()+1; 
      //XSSFRow removingRow = sheet.getRow(lastRowNum); 


      if(file.isFile() && file.exists()) 
      { 

       for (int i = lastRowNum; i>= lastRowNum-10 ; i--) 
       { 
       XSSFRow removingRow = sheet.getRow(i); 
       sheet.removeRow(removingRow); 
       } 

      } 

      else 
      { 
       System.out.println("Error in opening the file"); 
      } 
    } 
    } 

錯誤:

Exception in thread "main" java.lang.NullPointerException
at org.apache.poi.xssf.usermodel.XSSFSheet.removeRow(XSSFSheet.java:1914) at Sample1.main(Sample1.java:27)

JAR文件:

dom4J-1.6.1 
poi-3.16 
poi-3.17-beta 
poi-ooxml-3.15.0 
poi-ooxml-schemas-3.15.0 
xmlbeans-2.6.0 
commons-collections4-4.0 
commons-collections4-4.1 
commons-codec-1.10 
commons-logging-1.2 
maven-ant-tasks-2.1.3 

任何幫助表示讚賞。

在此先感謝。

+0

爲什麼在'+ 1''INT lastRowNum = sheet.getLastRowNum()+ 1;'?爲什麼'if(file.isFile()&& file.exists())'?如果'FileInputStream'能夠爲這個文件創建一個'FileInputStream',那麼它**必須是一個文件並且**必須存在。否則'FileNotFoundException'會被拋出。 –

回答

1

差一錯誤:

for (int i = lastRowNum; i>= lastRowNum-10 ; i--) 

應該是:

for (int i = lastRowNum - 1; i>= Math.max(lastRowNum-10, 0) ; i--)