如何使用JFileChooser在java中保存文件

时间:2014-11-14 07:48:40

标签: java excel swing jfilechooser

我正在使用java swing开发一个基于桌面的软件,需要以pdf和excel文件导出报告,并接受来自用户的路径。我有pdf和excel文件的导出报告,但现在我想接受来自用户的路径,用户必须为该文件命名。

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());
        }
      }
    }

这是我的代码,它只在当前目录中创建excel文件并保存文件,并且不接受用户的文件名。

任何人都可以建议我吗?

2 个答案:

答案 0 :(得分:3)

您只需在FileSave中创建一个空文件。

您必须从方法中返回所选文件名,并使用调用中返回的文件名

FileOutputStream fileOut =  new FileOutputStream(filename)

BWT java代码约定假设方法名称不是从大写字母

开始

答案 1 :(得分:0)

你可以试试这个。

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.");
            } 
        }
        }

}