简体   繁体   English

如何将JTable导出到.csv文件?

[英]How to export a JTable to a .csv file?

Like the title implies, i am looking for a way to export a jtable with data to a .csv file . 就像标题暗示的那样,我正在寻找一种将带有数据的jtable导出到.csv file I am not looking for other options then CSV , because CSV is the requirement for my program. 我不是在寻找其他选项,而是CSV ,因为CSV是我的程序的要求。

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. 我一直在寻找某些东西,比如apache.camel bindy ,我找不到足够的信息来理解如何使用它。

What is recommended? 推荐什么? If someone has a decent example of the usage of bindy I wouldn't mind either. 如果某人有一个体面的使用bindy例子,我也不介意。

Friendly regards, 友好的问候,

Skillcoil Skillcoil

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. 您可以使用apache poi从JTable生成Excel文件,然后使用此处的代码将XLS转换为CSV文件使用Java将XLS文件导出为CSV文件。

I actually use this way to generate CSV files 我实际上用这种方式生成CSV文件

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();
        }
    }

what about a little for-loop? 怎么样一个for循环? The TableModel provides all nessesary data, such as row count, column count, and the data. TableModel提供所有必要的数据,例如行数,列数和数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM