csvescapingjxtable

tab escape sequence not working when exporting from JXTable to excel (.csv) file


i am trying to export data from a JXTable to a .csv file(excel). i am using the following code for this:

public void exportToExcel(NGAFStandardTable table, File file){
        int i = 0;
        int j = 0;
        try{

            TableModel model = table.getModel();
            FileWriter excel = new FileWriter(file);

            for (i = 0; i < model.getColumnCount(); i++) {
                excel.write(model.getColumnName(i) + "\t");
            }

            excel.write("\n");

            for (i = 0; i < model.getRowCount(); i++){
                for (j = 0; j < (model.getColumnCount()); j++){
                    if(model.getValueAt(i,j) == null){
                        excel.write("" + "\t");
                    }
                    else { 
                        excel.write(model.getValueAt(i,j).toString() + "\t");
                    }
                }
                excel.write("\n");
            }

            excel.close();
        }
        catch(IOException e) {
            System.out.println(e);
        }
    }

the result is i am geting a csv file which has all the values from the table but the values for each row is in a single cell(for eg., A1, A2, A3). i.e., all the values for row1 is in A1 cell, and so on... i am using tab escape sequence("\t") so the data moves to next column but its not happening. kindly suggest


Solution

  • it worked when i used "," as the delimeter in place of "\t": excel.write(model.getValueAt(i, j).toString() + ",");