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 da
The following code uses substrings to allow for the columns to be orderly within the textfile. Its a bit messy but the first for loop handles column headers and the second for loop handles all the data. If you want to change the size of each piece of data change 20 to your prefered size.
BufferedWriter bfw = new BufferedWriter(new FileWriter(
"Data.txt"));
for (int i = 0; i < table.getColumnCount(); i++) {//first loop is used for titles of each column
String name = String.valueOf(table.getColumnName(i));
if (name.length() > 20) {//20 (characters long) is the constant I chose to make each value
name = name.substring(0, 20);
} else if (name.length() == 20) {
} else {
String spaces = "";
int diff = 20 - name.length();
while (diff > 0) {
spaces = spaces + " ";
diff--;
}
name = name.concat(spaces);
}
bfw.write(name);
bfw.write("\t");
}
for (int i = 0; i < table.getRowCount(); i++) {//for all the data in the Jtable excluding column headers
bfw.newLine();
for (int j = 0; j < table.getColumnCount(); j++) {
if (table.getValueAt(i, j) == null) {
bfw.write(" ");
bfw.write("\t");
}
else {
String name = String.valueOf((table
.getValueAt(i, j)));
if (name.contains("(")) {
name = name.substring(0, name.indexOf("("));
}
if (name.length() > 20) {
name = name.substring(0, 20);
} else if (name.length() == 20) {
} else {
String spaces = "";
int diff = 20 - name.length();
while (diff > 0) {
spaces = spaces + " ";
diff--;
}
name = name.concat(spaces);
}
bfw.write(name);
bfw.write("\t");
}
}
}