当该行的第一列为空时,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();
}
}
输出
excel read successfully
Exception in thread "main" java.lang.NullPointerException
at DataDrivern.ExcelWrite.main(ExcelWrite.java:22)
测试2:第一列不为空
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();
}
}
运行代码后
答案 0 :(得分:1)
错误使用方法而不是getRow ,您必须使用createRow
ws.createRow(0).createCell(0).setCellValue("test");
这会将字符串“ test”写入第0行和第0列