How to export a JTable to a .csv file?

自作多情 提交于 2019-12-23 05:04:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!