简体   繁体   中英

Exporting jtable data into Excel

I want to export jtable data into Excel.firstly I have to save the excel file. But I want to directly export jtable contents into Excel and after that I want to save excel file.Problem is that if the file is saved first and if have to export more than one jtable into excel all of them will be over write because of file name.I don't know where I am wrong. Plz suggest me some idea.Thanks in advance! Here following is the code I am using:-

ExcelExporter exp = new ExcelExporter();
File file = new File("abc.xls");//Note that i'm actually saving the file first
exp.exportTable(table1, file);

class ExcelExporter
{
    public ExcelExporter()
    {}
    public void exportTable(JTable table, File file) throws IOException
    {
         TableModel model = table.getModel();
         FileWriter excel = new FileWriter(file);
         for(int i = 0; i < model.getColumnCount(); i++)
         {
           excel.write(model.getColumnName(i) + "\t");
         }
        excel.write("\n");
        for(int i=0; i< model.getRowCount(); i++) {
         for(int j=0; j < model.getColumnCount(); j++) {
           excel.write(model.getValueAt(i,j).toString()+"\t");
        }
       excel.write("\n");
    }
     excel.close();
  }
}

Instead writing directly to excel, first read that excel file put all the data inside in memory data structure like list,map. Then the value that has to be written in excel is appended inside in memory data structure. At the end write the whole in memory data to the excel sheet.

Try Apache POI library. Here are some examples. http://poi.apache.org/spreadsheet/examples.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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