将JTable保存为文本文件 [英] Saving JTable as text file
问题描述
我正在保存包含来自JTable的数据的.txt和.doc文件。在它保存的那一刻,它将文本放在表格中,但是由于数据的长度不同而不适合。所以我想把日期布局如下:
I am saving a .txt and .doc file containing the data from my JTable. At the minute when it saves it lays the text out like its in a table, but due to different lengths of data it does not fit. So I am trying to get the date to lay out as follows:
第1列名称:第1行第1列数据
Column 1 name: row 1 column 1 data
第2列名称:第1行第2列数据
Column 2 name: row 1 column 2 data
第3列名称:第1行第3列数据
Column 3 name: row 1 column 3 data
第4列名称:第1行第4列数据
Column 4 name: row 1 column 4 data
第1列名称:第2行第1列数据
Column 1 name: row 2 column 1 data
列2名称:第2行第2列数据
Column 2 name: row 2 column 2 data
第3列名称:第2行第3列数据
Column 3 name: row 2 column 3 data
第4列名称:第2行第4列数据
Column 4 name: row 2 column 4 data
等。
我现在的代码是:
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();
}
}
}
但请记住我的每个表都有不同的列数和行数。
我试过保存数组中的列和数据,我觉得这是解决问题的正确方法,但我无法弄清楚如何按照我提到的顺序打印它,
But please keep in mind that each of my tables has different number of columns and rows. Ive tried saving the columns and data in arrays, and I have a feeling this is the right way to go around the problem but I cant figure out how to print it in the order i mentioned,
推荐答案
算法非常简单:
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));
}
}
这篇关于将JTable保存为文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!