该行的第一列为空时,Excel Write不起作用

时间:2018-08-19 15:54:37

标签: java excel selenium selenium-webdriver

当该行的第一列为空时,excel写不起作用。第二列和其余列的值还检查第一列是否已填充或为空。任何背后的原因或如何解决这个问题。

测试1:第一列为空

        package DataDrivern;

        import java.io.File;
        import java.io.FileInputStream;
        import java.io.FileOutputStream;

        import org.apache.poi.xssf.usermodel.XSSFSheet;
        import org.apache.poi.xssf.usermodel.XSSFWorkbook;

        public class ExcelWrite {

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

                File src=new File("D:\\Selenium Learning\\input.xlsx");
                FileInputStream fis=new FileInputStream(src);
                XSSFWorkbook wb=new XSSFWorkbook(fis);
                XSSFSheet ws=wb.getSheet("Sheet2");

                System.out.println("excel read successfully");

                ws.getRow(0).createCell(0).setCellValue("test");

                FileOutputStream fos=new FileOutputStream(src);
                wb.write(fos);
                wb.close();


            }

        }

enter image description here

输出

        excel read successfully
        Exception in thread "main" java.lang.NullPointerException
            at DataDrivern.ExcelWrite.main(ExcelWrite.java:22)

测试2:第一列不为空

在运行代码之前: enter image description here

        package DataDrivern;

        import java.io.File;
        import java.io.FileInputStream;
        import java.io.FileOutputStream;

        import org.apache.poi.xssf.usermodel.XSSFSheet;
        import org.apache.poi.xssf.usermodel.XSSFWorkbook;

        public class ExcelWrite {

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

                File src=new File("D:\\Selenium Learning\\input.xlsx");
                FileInputStream fis=new FileInputStream(src);
                XSSFWorkbook wb=new XSSFWorkbook(fis);
                XSSFSheet ws=wb.getSheet("Sheet2");

                System.out.println("excel read successfully");

                ws.getRow(0).createCell(0).setCellValue("test");

                FileOutputStream fos=new FileOutputStream(src);
                wb.write(fos);
                wb.close();


            }

        }

运行代码后

enter image description here

1 个答案:

答案 0 :(得分:1)

错误使用方法而不是getRow ,您必须使用createRow

ws.createRow(0).createCell(0).setCellValue("test");

这会将字符串“ test”写入第0行和第0列