如何将 JTable 导出到 .csv 文件? [英] How to export a JTable to a .csv file?
本文介绍了如何将 JTable 导出到 .csv 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
就像标题所暗示的那样,我正在寻找一种将带有数据的 jtable 导出到 .csv 文件
的方法.我不是在寻找其他选项然后 CSV
,因为 CSV
是我的程序的要求.
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.
我一直在看某些东西,比如 apache.camel
的 bindy
把我找不到足够的信息来理解如何使用它.
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.
有什么推荐?如果有人有一个使用 bindy
的好例子,我也不介意.
What is recommended? If someone has a decent example of the usage of bindy
I wouldn't mind either.
亲切的问候,
技能线圈
推荐答案
是这样的:
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();
}
}
这篇关于如何将 JTable 导出到 .csv 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文