Question

I'm trying, to save an excel file using jxl, but when I try to save the file have to retype and save plain without content. I am using a class to generate the excel file.

public class lsheet {
    public void fillData(JTable table, File file){
        try{
           WritableWorkbook workbook1 = Workbook.createWorkbook(file);
            WritableSheet sheet1 = workbook1.createSheet("Data 1", 0);
            TableModel model = table.getModel();
            for (int i = 0; i < model.getColumnCount(); i++) {
                Label column = new Label(i, 0, model.getColumnName(i));
                sheet1.addCell(column);
            }
            int j = 0;
            for (int i = 0; i < model.getRowCount(); i++) {
                for (j = 0; j < model.getColumnCount(); j++) {
                    Label row = new Label(j, i + 1,
                            model.getValueAt(i, j).toString());
                    sheet1.addCell(row);
                }
            }
            workbook1.write();
            workbook1.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

this action button, how do, to display the filechooser with the loaded data in the table?

lsheet sht = new lshtCalc();
java.util.Date today = new java.util.Date();
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
try{
  String name="";
  JFileChooser file=new JFileChooser();
  file.showSaveDialog(this);
  File save =file.getSelectedFile();
  if(save !=null){
      FileWriter save = new FileWriter(save + ".xls");
      sht.fillData(tblCliente, new File("Report-Client-"+ sdf2.format(today).toString()+".xls"));
      save.close();
  }
}catch(Exception ex){
    ex.printStackTrace();
}
Was it helpful?

Solution

The file object you are passing to the fillData method is something that you create with time stamp so it will create a file with that name in your workspace with the contents from your JTable.

The file you select using JFileChooser is only used to create a filewriter and to close it. SO it will create an empty file in the location you choose.

Try this change:

          JFileChooser file=new JFileChooser();
          file.showSaveDialog(this);
          File save =file.getSelectedFile();
          if(save !=null){

              sht.fillData(tblCliente, save);

          }
        }catch(Exception ex){
            ex.printStackTrace();
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top