Reputation: 189
I am trying to delete last 10 rows using Apache-POI. I tried to find solutions online, no luck. My code:
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");
}
}
}
Error:
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 Files:
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
Any help is appreciated.
Thanks in advance.
Upvotes: 0
Views: 477
Reputation: 9100
Off-by-one error:
for (int i = lastRowNum; i>= lastRowNum-10 ; i-- )
should be:
for (int i = lastRowNum - 1; i>= Math.max(lastRowNum-10, 0) ; i-- )
Upvotes: 1