Java 将Jtable写入Excel时出现空指针异常
我正在尝试从Jtable到Excel中写入日期 这是我的公开义务:Java 将Jtable写入Excel时出现空指针异常,java,excel,nullpointerexception,jtable,Java,Excel,Nullpointerexception,Jtable,我正在尝试从Jtable到Excel中写入日期 这是我的公开义务: public void toExcel(JTable table, File file){ try{ TableModel model = table.getModel(); FileWriter excel = new FileWriter(file); for(int i = 0; i < model.getColumnCount(); i++){
public void toExcel(JTable table, File file){
try{
TableModel model = table.getModel();
FileWriter excel = new FileWriter(file);
for(int i = 0; i < model.getColumnCount(); i++){
excel.write(model.getColumnName(i) + "\t");
}
excel.write("\n");
for(int i=0; i< model.getRowCount(); i++) {
for(int j=0; j < model.getColumnCount(); j++) {
excel.write(model.getValueAt(i,j).toString()+"\t");
}
excel.write("\n");
}
excel.close();
}catch(IOException e){ System.out.println(e); }
}
但无论我在代码中做了什么更改或尝试了什么,我总是会得到一个NullPointer异常,并且我创建的文件总是空的。。有人知道我做错了什么或者应该添加到我的代码中吗?model.getValueAt(i,j)
可能会返回null,因此在使用返回值之前应该检查null:
if (model.getValueAt(i,j) != null)
excel.write(model.getValueAt(i,j).toString()+"\t");
model.getValueAt()
为null
,因此会出现此异常
NullPointerException:
Thrown when an application attempts to use null in a case where an object is required. These include:
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
NullPointerException:
当应用程序在需要对象的情况下尝试使用null时引发。这些措施包括:
-调用空对象的实例方法。
-访问或修改空对象的字段。
-将null的长度视为数组。
-像数组一样访问或修改null的插槽。
-将null作为可丢弃的值抛出。
因此,在调用model.setValueAt
时,应检查以避免使用null
,删除“.toString()”调用。Java将自动在这个表达式中使用to字符串,如果有null,您将看到null在文件中的位置。通过这种方式,您可以避免使用空的行/列,或者重新考虑要输出到excel的值
NPE检查也可以做到这一点-只是您无法理解丢失的数据在哪里。您究竟在哪里(哪一行)得到异常?excel.write(model.getValueAt(i,j).toString()+“\t”);那我该怎么办呢?我有一个应用程序,在按下按钮后将数据写入jtable,当我按下按钮保存jtable时,jtable中肯定有数据?@VanpeltJ表中的所有单元格中都有值吗?我的单元格中都有值和文本。这是一张显示网球比赛结果的表格…我现在已经添加了这个,至少我不再有空的例外。我删除了模型的初始化,现在它可以工作了。非常感谢。 NullPointerException: Thrown when an application attempts to use null in a case where an object is required. These include: - Calling the instance method of a null object. - Accessing or modifying the field of a null object. - Taking the length of null as if it were an array. - Accessing or modifying the slots of null as if it were an array. - Throwing null as if it were a Throwable value.