删除最后一行Excel时出错 - Apache POI

时间:2017-07-24 19:28:55

标签: java excel apache-poi

我正在尝试使用Apache-POI删除最后10行。我试着在网上找到解决方案,没有运气。 我的代码:

 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");
            }   
    }   
    }

错误:

  

线程中的异常" main"显示java.lang.NullPointerException
           在org.apache.poi.xssf.usermodel.XSSFSheet.removeRow(XSSFSheet.java:1914)            在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

感谢任何帮助。

提前致谢。

1 个答案:

答案 0 :(得分:1)

一分错误:

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

应该是:

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