package com.bear.util;
import java.io.*;
import javax.swing.*;
import javax.swing.table.*;
public class ExcelUtil {
public void exportTable(JTable table,String title) throws IOException {
TableModel model = table.getModel();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("."));//设置当前目录
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.addChoosableFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File file) {
if (file.isDirectory())
return true;
return (file.getName().indexOf("xls") != -1);
}
public String getDescription() {
return "Microsoft Excel文件(*.xls)";
}
});
//fileChooser.showSaveDialog(null);
int returnVal =fileChooser.showSaveDialog(fileChooser);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file.exists()) {
int copy = JOptionPane.showConfirmDialog(null,"是否要覆盖当前文件?", "保存", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if (copy == JOptionPane.YES_OPTION)
fileChooser.approveSelection();
else
return;
}
else
fileChooser.approveSelection();
FileWriter out = new FileWriter(file);
out.write(title + "\n\n");
for(int i=0; i < model.getColumnCount(); i++)
out.write(model.getColumnName(i) + "\t");
out.write("\n");
for(int i=0; i< model.getRowCount(); i++) {
for(int j=0; j < model.getColumnCount(); j++) {
out.write(model.getValueAt(i,j).toString()+"\t");
}
out.write("\n");
}
out.close();
JOptionPane.showMessageDialog(null, "EXCEL文件导出成功!","成功",RMATION_MESSAGE);
}
}
}。