有沒有辦法將 JTable 資料保存到 Excel 中?我想保存我從程式輸入的資料,從 JTable 到 CSV 檔案。
我想要它,以便有一個按鈕可以將輸入的資料從 jform 保存到 jtable 中,然后保存到 CSV 檔案中。
uj5u.com熱心網友回復:
這可能會幫助您:-
寫入 csv 檔案的方法。
public static void exportToCSV(JTable table,
String path) {
try {
TableModel model = table.getModel();
FileWriter csv = new FileWriter(new File(path));
for (int i = 0; i < model.getColumnCount(); i ) {
csv.write(model.getColumnName(i) ",");
}
csv.write("\n");
for (int i = 0; i < model.getRowCount(); i ) {
for (int j = 0; j < model.getColumnCount(); j ) {
csv.write(model.getValueAt(i, j).toString() ",");
}
csv.write("\n");
}
csv.close();
} catch (IOException e) {
System.out.println("Error " e);
}
}
要閱讀并將其顯示給 JTable,您可以使用OpenCSV。
CSVReader reader = new CSVReader(new FileReader("file.csv"));
List list = reader.readAll();
JTable table = new JTable(list.toArray());
希望能幫助到你!
uj5u.com熱心網友回復:
據我所知,沒有 JTable 的“神奇功能”可以做到這一點。JTable 是一個 UI 組件,您要求的是資料功能,而不是用戶界面功能。并且它與 eclipse 沒有太大關系,它只是用于撰寫代碼的 IDE。
我認為您可能正在尋找的是JTable 所基于的模型。我想到的第一個解決方案是更改該模型代碼,使其具有一種以您想要的格式寫出資料的方法;然后 UI 上的(另一個)按鈕將在模型上呼叫此方法以在用戶選擇時寫出資料。可能還有其他方法可以完成此操作,但這似乎是最直接和最簡單的方法。
uj5u.com熱心網友回復:
你可以試試這個代碼:
public static boolean convertToCSV(JTable table,
String path) {
try {
TableModel model = table.getModel();
FileWriter csv = new FileWriter(new File(path));
for (int i = 0; i < model.getColumnCount(); i ) {
csv.write(model.getColumnName(i) ",");
}
csv.write("\n");
for (int i = 0; i < model.getRowCount(); i ) {
for (int j = 0; j < model.getColumnCount(); j ) {
csv.write(model.getValueAt(i, j).toString() ",");
}
csv.write("\n");
}
csv.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/337212.html
