Java 如何使用 JFileChooser 保存由 Apache POI 创建的 excel 文件

Java how to user JFileChooser to save a excel file created by Apache POI

我想将电子表格文件保存到用户自定义的文件夹中,有人建议使用JFileChooser,但我实际上不知道如何实现。我在这里有我当前的示例代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Example {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        XSSFWorkbook workbook;
        File file = new File("example.xlsx");
        if (file.exists() == false) {
            workbook = new XSSFWorkbook();
            XSSFSheet exampleSheet = workbook.createSheet("1");
            XSSFRow firstRow = exampleSheet.createRow(1);
            XSSFCell cell = firstRow.createCell(0);
            cell.setCellValue("value");

            try ( 
                //Write the workbook in file system
                FileOutputStream out = new FileOutputStream(file)) {               
                    workbook.write(out);
                }
        } else {
            // Sheet already exists
            System.out.println("File already exist");
        }
    }

}

目前只能将文件保存到默认项目目录。但我希望它以用户自定义的文件名保存到用户选择的路径中。 JFileChooser 似乎是个不错的选择,但有人可以告诉我如何在我的案例中使用它吗?

public class Example {
    static String fileDictName = "";

    public static void main(String[] args) throws FileNotFoundException, IOException {
        XSSFWorkbook workbook;

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Open the file"); //name for chooser
        FileFilter filter = new FileNameExtensionFilter("Files", ".xlsx"); //filter to show only that
        fileChooser.setAcceptAllFileFilterUsed(false); //to show or not all other files
        fileChooser.addChoosableFileFilter(filter);
        fileChooser.setSelectedFile(new File(fileDictName)); //when you want to show the name of file into the chooser
        fileChooser.setVisible(true);
        int result = fileChooser.showOpenDialog(fileChooser);
        if (result == JFileChooser.APPROVE_OPTION) {
            fileDictName = fileChooser.getSelectedFile().getAbsolutePath();
        } else {
            return;
        }

        File file = new File(fileDictName);
        if (file.exists() == false) {
            workbook = new XSSFWorkbook();
            XSSFSheet exampleSheet = workbook.createSheet("1");
            XSSFRow firstRow = exampleSheet.createRow(1);
            XSSFCell cell = firstRow.createCell(0);
            cell.setCellValue("value");

            try (
                    //Write the workbook in file system
                    FileOutputStream out = new FileOutputStream(file)) {
                workbook.write(out);
            }
        } else {
            // Sheet already exists
            System.out.println("File already exist");
        }
    }

}

当我们要用它来保存文件时,我们需要:

JFileChooser fileChooser = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("Files", ".xlsx");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setDialogTitle("Save the dictionary file"); 
fileChooser.setSelectedFile(new File(fileDictName));
int userSelection = fileChooser.showSaveDialog(fileChooser);
if (userSelection == JFileChooser.APPROVE_OPTION) {
    fileDictName = fileChooser.getSelectedFile().getAbsolutePath();
}

这是一个例子:

JFileChooser jfc = new JFileChooser();
int res = jfc.showSaveDialog(this);
if (res != JFileChooser.APPROVE_OPTION) {
            return;
}
File file = jfc.getSelectedFile();

public void importExcelToJtableJava() {

    File excelFile;
    FileInputStream excelFIS = null;
    BufferedInputStream excelBIS = null;
    XSSFWorkbook excelImportToJTable = null;
    String defaultCurrentDirectoryPath = "C:\Users\Authentic\Desktop";
    JFileChooser excelFileChooser = new JFileChooser(defaultCurrentDirectoryPath);
    excelFileChooser.setDialogTitle("Select Excel File");
    FileNameExtensionFilter fnef = new FileNameExtensionFilter("EXCEL FILES", "xls", "xlsx", "xlsm");
    excelFileChooser.setFileFilter(fnef);
    int excelChooser = excelFileChooser.showOpenDialog(null);
    if (excelChooser == JFileChooser.APPROVE_OPTION) {
        try {
            excelFile = excelFileChooser.getSelectedFile();
            excelFIS = new FileInputStream(excelFile);
            excelBIS = new BufferedInputStream(excelFIS);
            excelImportToJTable = new XSSFWorkbook(excelBIS);
            XSSFSheet excelSheet = excelImportToJTable.getSheetAt(0);

            for (int row = 0; row < excelSheet.getLastRowNum(); row++) {
                XSSFRow excelRow = excelSheet.getRow(row);

                XSSFCell excelName = excelRow.getCell(0);
                XSSFCell excelGender = excelRow.getCell(1);
                XSSFCell excelProgrammingLanguage = excelRow.getCell(2);
                XSSFCell excelSubject = excelRow.getCell(3);
                XSSFCell excelImage = excelRow.getCell(4);

                JLabel excelJL = new JLabel(new ImageIcon(new ImageIcon(excelImage.getStringCellValue()).getImage().getScaledInstance(60, 60, Image.SCALE_SMOOTH)));
                model.addRow(new Object[]{excelName, excelGender, excelProgrammingLanguage, excelSubject, excelJL});
            }
            JOptionPane.showMessageDialog(null, "Imported Successfully !!.....");
        } catch (IOException iOException) {
            JOptionPane.showMessageDialog(null, iOException.getMessage());
        } finally {
            try {
                if (excelFIS != null) {
                    excelFIS.close();
                }
                if (excelBIS != null) {
                    excelBIS.close();
                }
                if (excelImportToJTable != null) {
                    excelImportToJTable.close();
                }
            } catch (IOException iOException) {
                JOptionPane.showMessageDialog(null, iOException.getMessage());
            }
        }
    }
}  

}