简体   繁体   English

将JTable数据导出到Excel

[英]Exporting jtable data into Excel

I want to export jtable data into Excel.firstly I have to save the excel file. 我想将jtable数据导出到Excel中。首先我必须保存excel文件。 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. 但是我想直接将jtable内容导出到Excel中,然后再保存excel文件。问题是,如果先保存文件,并且必须将多个jtable导出到excel中,那么由于文件的原因,所有这些文件都会被覆盖名字。我不知道我在哪里错。 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. 而不是直接写入excel,而是先读取excel文件,然后将所有数据放入列表,映射等内存数据结构中。 Then the value that has to be written in excel is appended inside in memory data structure. 然后将必须用excel写入的值附加到内存数据结构的内部。 At the end write the whole in memory data to the excel sheet. 最后,将整个内存数据写入Excel工作表。

Try Apache POI library. 尝试Apache POI库。 Here are some examples. 这里有些例子。 http://poi.apache.org/spreadsheet/examples.html http://poi.apache.org/spreadsheet/examples.html

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

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