Wednesday, February 16, 2011

how to export jtable data to excel file

Hello friends,
following is the  function which helps to export tables data to the excel file.
exportTable()  function takes two parameter one is table and another one is the file name

eg. exportTable(table, new File("D:\tabledata.xls"));

public void exportTable(JTable table, File file) throws IOException {
            TableModel model = table.getModel();
            FileWriter out = new FileWriter(file);
            for(int i=0; i < model.getColumnCount(); i++) {
        out.write(model.getColumnName(i) + "\t");
            }
            out.write("\n");

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

        out.close();
        System.out.println("write out to: " + file);
}

If any queries and any suggestions regarding this please mention

2 comments:

  1. thank you for this! but how can you delete the last tab delimiter in every last column of the file.

    ReplyDelete
  2. can you please do this using file chooser and save export excel file with xlsx file extension

    ReplyDelete