我正在保存包含 JTable 中的数据的 .txt 和 .doc 文件。在保存时,它会像在表格中一样布置文本,但由于数据长度不同,它不适合。所以我试图将日期安排如下:
第1列名称:第1行第1列数据
第2列名称:第1行第2列数据
第3列名称:第1行第3列数据
第4列名称:第1行第4列数据
第1列名称:第2行第1列数据
第2列名称:第2行第2列数据
第3列名称:第2行第3列数据
第4列名称:第2行第4列数据
etc.
我现在的代码是:
private void saveResultsActionPerformed(ActionEvent evt) {
int returnVal = fileChooser.showSaveDialog(NewJFrame.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
PrintWriter os = new PrintWriter(file);
os.println("");
for (int col = 0; col < table.getColumnCount(); col++) {
os.print(table.getColumnName(col) + "\t");
}
os.println("");
os.println("");
for (int i = 0; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
os.print(table.getValueAt(i, j).toString() + "\t");
}
os.println("");
}
os.close();
System.out.println("Done!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
但请记住,我的每个表都有不同的列数和行数。
我尝试过将列和数据保存在数组中,我有一种感觉这是解决问题的正确方法,但我不知道如何按照我提到的顺序打印它,
该算法非常简单:
for (int row = 0; row < table.getRowCount(); row++) {
for (int col = 0; col < table.getColumnCount(); col++) {
os.print(table.getColumnName(col));
os.print(": ");
os.println(table.getValueAt(row, col));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)