我创建了一个注册表单,它从用户那里收集数据,并将其显示到 Jtable 中,然后我想让用户按下按钮将 Jtable 内容导出到 excel 表单。在显示表中,它可以显示所有用户输入,但是当我导出到excel时,它只显示columnNames和第一行数据,所以我想知道我是否做错了?
用户输入:
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
String[] columnNames = new String[] {"First Name", "Last Name", "Email", "Degree", "Year", "Event"};
Object[][] tabledata = new Object[1][6];
String fn = FirstName.getText();
String ln = LastName.getText();
String em = Email.getText();
String re = ReEnter.getText();
String de = Degree.getSelectedItem().toString();
String yr = Year.getSelectedItem().toString();
String ev = EventDate.getSelectedItem().toString();
ArrayList<String> data = new ArrayList<String>();
data.add(fn);
data.add(ln);
data.add(em);
data.add(de);
data.add(yr);
data.add(ev);
list.add(data);
//Set fields to empty
FirstName.setText("");
LastName.setText("");
Email.setText("");
ReEnter.setText("");
Degree.setSelectedItem(null);
Year.setSelectedItem(null);
EventDate.setSelectedItem(null);
// print data to table
Object[][] temp = new Object[tabledata.length+1][6];
for(int i=0;i<tabledata.length;i++){
for(int j=0;j<6;j++){
temp[i][j] = tabledata[i][j];
}
temp[tabledata.length-1][0]= fn;
temp[tabledata.length-1][1]= ln;
temp[tabledata.length-1][2]= em;
temp[tabledata.length-1][3]= de;
temp[tabledata.length-1][4]= yr;
temp[tabledata.length-1][5]= ev;
}
tabledata = temp;
table.setModel(new DefaultTableModel(tabledata, columnNames));
}
}
导出数据到excel:
try {
TableModel model = table.getModel();
File file = new File("member.xls");
FileWriter output = new FileWriter(file);
for(int i = 0; i <model.getColumnCount(); i++){
output.write(model.getColumnName(i) + "\t");
}
output.write("\n");
for(int k=0;k<model.getRowCount();k++) {
for(int j=0;j<model.getColumnCount();j++) {
output.write(model.getValueAt(k,j).toString()+"\t");
}
output.write("\n");
output.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
![运行程序][1]:http: //i.stack.imgur.com/T99L5.png ![导出的excel文件][2]:http: //i.stack.imgur.com/ZGy3Z.png