如何在java中保存扩展名为.xls的excel文件?
Posted
技术标签:
【中文标题】如何在java中保存扩展名为.xls的excel文件?【英文标题】:How to save an excel file with .xls extension in java? 【发布时间】:2015-04-14 07:54:04 【问题描述】:我必须保存一个带有 .xls 扩展名的 excel 文件。我希望在使用文件选择器设计的保存文件对话框中选择文件类型后,默认情况下应该采用扩展名。我已经尝试了这么多代码但仅当我将文件名指定为 filename.xls 时,它才会以 .xls 格式保存文件
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.");
【问题讨论】:
可能重复***.com/questions/17010647/… 【参考方案1】:您需要使用此选项将文件名设置为*.xls:
chooser.setSelectedFile("*.xls");
对于文件类型下拉菜单,设置以下选项:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files","xls","excel");
chooser.addChoosableFileFilter(filter);
chooser.setFileFilter(filter);
chooser.setAcceptAllFileFilterUsed(false);
【讨论】:
【参考方案2】:我这样做了,它奏效了。
if(!file1.exists())
FileOutputStream fileOut = new FileOutputStream(file1+".xls");
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your Excel file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
【讨论】:
以上是关于如何在java中保存扩展名为.xls的excel文件?的主要内容,如果未能解决你的问题,请参考以下文章
excel提示 打开的文件.xls的格式与文件扩展名不一致怎么办
为啥我用java导出的.xlsx出现扩展名无效,但是.xls是正常的