How to save file in java using JFileChooser

4.3k Views Asked by At

I am developing one desktop based software using java swing which required to export reports in pdf and excel file and will accept path from user. I have export reports in pdf and excel file but now I wants to accept path from user and user have to give name to that file.

try
{
    String filename="sales111.xls" ;
    HSSFWorkbook hwb=new HSSFWorkbook();
    HSSFSheet sheet =  hwb.createSheet("Sales Report in Excel");

    HSSFRow rowhead=   sheet.createRow((short)0);
        rowhead.createCell((short) 0).setCellValue("Invoice Numberr");
        rowhead.createCell((short) 1).setCellValue("date");
        rowhead.createCell((short) 2).setCellValue("Customer Name");
        rowhead.createCell((short) 3).setCellValue("customer Code");
        rowhead.createCell((short) 4).setCellValue("Stock Item Name");
        rowhead.createCell((short) 5).setCellValue("Product Quantity");
        rowhead.createCell((short) 6).setCellValue("Product Rate");
        rowhead.createCell((short) 7).setCellValue("Total Amount");
        rowhead.createCell((short) 8).setCellValue("Tax Category");
        rowhead.createCell((short) 9).setCellValue("Tax Amount");
        rowhead.createCell((short) 10).setCellValue("Transport Charges");
        rowhead.createCell((short) 11).setCellValue("Net Amount");
        rowhead.createCell((short) 11).setCellValue("Credit Limit");

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/BOA", "root", "root");
        Statement st=con.createStatement();
        ResultSet rs=st.executeQuery("Select * from SalesVoucher");
        int i=1;

        while(rs.next())
        {
            HSSFRow row=   sheet.createRow((short)i);
            row.createCell((short) 0).setCellValue(rs.getString("innum"));
            row.createCell((short) 1).setCellValue(rs.getString("date"));
            row.createCell((short) 2).setCellValue(rs.getString("scname"));
            row.createCell((short) 3).setCellValue(rs.getString("sccode"));
            row.createCell((short) 4).setCellValue(rs.getString("stname"));
            row.createCell((short) 5).setCellValue(Integer.toString(rs.getInt("pquantity")));
            row.createCell((short) 6).setCellValue(Double.toString(rs.getDouble("prate")));
            row.createCell((short) 7).setCellValue(Double.toString(rs.getDouble("samount")));
            row.createCell((short) 8).setCellValue(Double.toString(rs.getDouble("staxcat")));
            row.createCell((short) 9).setCellValue(Double.toString(rs.getDouble("stamount")));
            row.createCell((short) 10).setCellValue(Double.toString(rs.getDouble("strans")));
            row.createCell((short) 11).setCellValue(Double.toString(rs.getDouble("stota")));
            row.createCell((short) 11).setCellValue(Integer.toString(rs.getInt("scredlim")));

            i++;
        }

        FileOutputStream fileOut =  new FileOutputStream(filename);
        hwb.write(fileOut);
        fileOut.close();
        System.out.println("Your Sales Report Excel file has been generated!");

        String name1="";

        FileSave(filename,name1);
} 
catch ( Exception ex ) 
{
    System.out.println(ex);
}
}
public void FileSave(final String title,final String name)
{
      final JFileChooser chooser=new JFileChooser();
    //  chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
      chooser.setDialogTitle(title);
      chooser.setCurrentDirectory(new File(System.getProperties().getProperty("user.dir")));
      chooser.setFileFilter(new javax.swing.filechooser.FileFilter()
      {
         public boolean accept(final File f)
        {
          return f.isDirectory();
        }
        public String getDescription(){
          return "Folder To Save In";
        }
      }
    );
      final int r=chooser.showSaveDialog(null);
      File file;

      if (r == JFileChooser.APPROVE_OPTION) 
      {
        if (name != null) 
        {
            file=new File(chooser.getSelectedFile().getPath() + File.separator + name);
        }
        else 
        {
            // file=new File(filename);
          file=new File(chooser.getSelectedFile().getPath());
        }
      }
    }

This is my code which creates excel file and saving file only in current directory and doesnt accept file name from user.

Can any one please suggest me?

2

There are 2 best solutions below

3
StanislavL On

You just create an empty file in your FileSave.

You have to return selected file name from the method and use the returned filename in the call

FileOutputStream fileOut =  new FileOutputStream(filename)

BWT java code convention supposes to have method names don't start from capital letter

1
Aparna Pathak On

You can try this.

public void FileSave() throws IOException
{

   JFileChooser chooser=new JFileChooser(".");

   FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files","xls","excel");

   chooser.addChoosableFileFilter(filter);


   chooser.setFileFilter(filter);
   chooser.setFileSelectionMode(chooser.FILES_AND_DIRECTORIES);
   chooser.setDialogTitle("Save File");
   chooser.setCurrentDirectory(new File(System.getProperties().getProperty("user.home")));
   chooser.setFileFilter(new javax.swing.filechooser.FileFilter()
   {
        public boolean accept(final File f)
        {
            return f.isDirectory()|| file.getAbsolutePath().endsWith(".xls");
        }

        public String getDescription()
        {
            return "Excel files (*.xls)";
        }
  });

  int returnVal1=chooser.showSaveDialog(this);
  if (returnVal1 == JFileChooser.APPROVE_OPTION) 
  {


        file1 = chooser.getSelectedFile();

        if(!file1.exists())
        {

            FileOutputStream fileOut =  new FileOutputStream(file1);
            hwb.write(fileOut);
            fileOut.close();
            System.out.println("\n Your Excel file has been generated!");
            JOptionPane.showMessageDialog(this,"File Created.");
        }
        else if(file1.exists())
        {
            int res=JOptionPane.showConfirmDialog(this,"File already exists.Do you wish to overwrite?");
            if(res == JOptionPane.YES_OPTION)
            {
                FileOutputStream fileOut =  new FileOutputStream(file1);
                hwb.write(fileOut);
                fileOut.close();
                System.out.println("\n Your Excel file has been generated!");
                JOptionPane.showMessageDialog(this,"File Created.");
            }
            else if(res == JOptionPane.NO_OPTION)
            {
                int returnVal2=chooser.showSaveDialog(this);
                if (returnVal2 == JFileChooser.APPROVE_OPTION) 
                {

                    File file2 = chooser.getSelectedFile();
                    if(!file2.exists())
                    {

                        FileOutputStream fileOut =  new FileOutputStream(file2);
                        hwb.write(fileOut);
                        fileOut.close();
                        System.out.println("\n Your Excel file has been generated!");
                        JOptionPane.showMessageDialog(this,"File Created.");
                    }

                }
            }
            else if (res == JOptionPane.CANCEL_OPTION) 
            {
                JOptionPane.showMessageDialog(this, "User cancelled operation.");
            } 
        }
        }

}