简体   繁体   中英

How to create a new excel file in a java application and saving it at the specified location?

I want to create a new excel file such that the name of the file is provided by the user at run time and save this file at the location on which user wants. I have tried some code but it creates a file with the same name everytime and at the same location.It does not ask user for filename and location.

private void buttonCALCULATEActionPerformed(java.awt.event.ActionEvent evt) {
filename="D:\\test.xls" ;
        HSSFWorkbook hwb=new HSSFWorkbook();
        HSSFSheet sheet =  hwb.createSheet("Report in Excel");

        HSSFRow rowhead=sheet.createRow((short)0);
        rowhead.createCell((short) 0).setCellValue("Plot Id");
        rowhead.createCell((short) 1).setCellValue("Species Name");
        FileOutputStream fileOut =  new FileOutputStream(filename);
        hwb.write(fileOut);
        fileOut.close();
        System.out.println("\n Your Excel file has been generated!");
        //String name1=" ";
        FileSave();
 }
public void FileSave() throws IOException
{

JFileChooser chooser=new JFileChooser("./");
FileNameExtensionFilter filter = new  FileNameExtensionFilter("Excel       files",".xls");     
  chooser.addChoosableFileFilter(filter);
  int returnVal1=chooser.showSaveDialog(this);

 // chooser.setFileFilter(filter);
  chooser.setFileSelectionMode(chooser.FILES_ONLY);
  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)";
    }
  }
);
 if (returnVal1 == JFileChooser.APPROVE_OPTION) 
  {
file1 = chooser.getSelectedFile();       
}
}

Put int returnVal1=chooser.showSaveDialog(this); this immeditaly before if (returnVal1 == JFileChooser.APPROVE_OPTION)

public void FileSave() throws IOException {

    JFileChooser chooser = new JFileChooser("./");
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel       files", ".xls");
    chooser.addChoosableFileFilter(filter);

    // chooser.setFileFilter(filter);
    chooser.setFileSelectionMode(chooser.FILES_ONLY);
    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();
    }
}

Change FileSave to return a File (or null if the user cancelled the file chooser)

public File FileSave() throws IOException {
    File file1 = null;
    //...
    return file1;
}

Ask for the file BEFORE you attempt to save it...

private void buttonCALCULATEActionPerformed(java.awt.event.ActionEvent evt) {
    File file = FileSave();
    if (file != null) {
        HSSFWorkbook hwb = new HSSFWorkbook();
        HSSFSheet sheet = hwb.createSheet("Report in Excel");

        HSSFRow rowhead = sheet.createRow((short) 0);
        rowhead.createCell((short) 0).setCellValue("Plot Id");
        rowhead.createCell((short) 1).setCellValue("Species Name");
        try (FileOutputStream fileOut = new FileOutputStream(file)) {
            hwb.write(fileOut);
        } catch (IOException exp) {
            exp.printStackTrace();
        }
        System.out.println("\n Your Excel file has been generated!");
    }
}

You might like to have a read through Code Conventions for the Java TM Programming Language , it will make it easier for people to read your code and for you to read others

I tried this and it worked 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.");
            } 
        }
        }
   // return file1;

}

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