问题
Like the title implies, i am looking for a way to export a jtable with data to a .csv file
. I am not looking for other options then CSV
, because CSV
is the requirement for my program.
I have been looking at certain things, like bindy
of apache.camel
put I couldn't find enough information to understand how to use it.
What is recommended? If someone has a decent example of the usage of bindy
I wouldn't mind either.
Friendly regards,
Skillcoil
回答1:
You can use apache poi to generate an Excel file from the JTable then use this code from here Converting XLS to CSV files Using Java to export XLS file to CSV file.
I actually use this way to generate CSV files
回答2:
It is something like that:
public void writeCSVfile(JTable table) throws IOException, ClassNotFoundException, SQLException{
Writer writer = null;
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
int nRow = dtm.getRowCount();
int nCol = dtm.getColumnCount();
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("file.txt"), "utf-8"));
//write the header information
StringBuffer bufferHeader = new StringBuffer();
for (int j = 0; j < nCol; j++) {
bufferHeader.append(dtm.getColumnName(j));
if (j!=nCol) bufferHeader.append(", ");
}
writer.write(bufferHeader.toString() + "\r\n");
//write row information
for (int i = 0 ; i < nRow ; i++){
StringBuffer buffer = new StringBuffer();
for (int j = 0 ; j < nCol ; j++){
buffer.append(dtm.getValueAt(i,j));
if (j!=nCol) buffer.append(", ");
}
writer.write(buffer.toString() + "\r\n");
}
} finally {
writer.close();
}
}
回答3:
what about a little for-loop? The TableModel provides all nessesary data, such as row count, column count, and the data.
来源:https://stackoverflow.com/questions/16436928/how-to-export-a-jtable-to-a-csv-file