簡體   English   中英

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

[英]How to save file in java using 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文件並保存文件,並且不接受用戶的文件名。

任何人都可以建議我嗎?

您只需在FileSave中創建一個空文件。

您必須從方法返回選定的文件名,並在調用中使用返回的文件名

FileOutputStream fileOut =  new FileOutputStream(filename)

BWT java代碼約定假設方法名稱不是從大寫字母開始

你可以試試這個。

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM