我正在保存一个 .txt 和 .doc 文件,其中包含我的 JTable 中的数据。在保存的那一刻,它像在表格中一样布置文本,但由于数据长度不同,它不适合。所以我试图让日期布局如下:
第 1 列名称:第 1 行第 1 列数据
第 2 列名称:第 1 行第 2 列数据
第 3 列名称:第 1 行第 3 列数据
第 4 列名称:第 1 行第 4 列数据
第 1 列名称:第 2 行第 1 列数据
第 2 列名称:第 2 行第 2 列数据
第 3 列名称:第 2 行第 3 列数据
第 4 列名称:第 2 行第 4 列数据
等等
我现在的代码是:
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));
}
}
关于java - 将 JTable 保存为文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14166269/