Java和POI的新手 我使用POI 3.15与Java,我想从JTable写入Excel。我的JTable很长(很多行),并且有不同的数据类型,如数字,字符串,空白和自定义日期格式。我如何在Java中编程,以便当我单击按钮时,来自JTable的数据写入具有相同数据类型的Excel。我得到一个java.lang.NullPointerExeption错误,因为我有一个空白单元格,我在Excel中最多有空白。 `
btnFil.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser save = new JFileChooser("c:\\test\\");
save.setDialogTitle("Save as...");
save.setFileFilter(new FileNameExtensionFilter("xls", "xlsx", "xlsm"));
int choose = save.showSaveDialog(null);
if(choose == JFileChooser.APPROVE_OPTION) {
XSSFWorkbook faktura = new XSSFWorkbook();
XSSFSheet sheet1 = faktura.createSheet("Under 7m3");
try{
TableModel tableModel = under.getModel();
for(int i=0; i<tableModel.getRowCount(); i++) {
XSSFRow newRow = sheet1.createRow(i);
for(int j=0; j<tableModel.getColumnCount(); j++) {
XSSFCell newCell = newRow.createCell((short) j);
if(i==0){
newCell.setCellValue(tableModel.getColumnName(j));
} else {
newCell.setCellValue(tableModel.getValueAt(i, j).toString());
}
}
}
FileOutputStream otp = new FileOutputStream(save.getSelectedFile()+".xlsx");
BufferedOutputStream bos = new BufferedOutputStream(otp);
faktura.write(bos);
bos.close();
otp.close();
JOptionPane.showMessageDialog(null, "Filen ble lagret!");
}catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
});
`