如何把Jtable的内容提取出来,生成一个excel,让用户自己选择生成路径。
上图
效果:点击导出,让用户选择保存路径,并且是excel格式的
思路:使用Jxl这个包,获得jtable的数据,然后生成一个excel,写数据进去
1、保存框
JFileChooser c = new JFileChooser();这个是弹出保存框
c.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Excel";//设置默认是Excel
}
@Override
public boolean accept(File f) {//只显示xls文件和文件夹
if(f.getName().endsWith(".xls")||f.isDirectory()) {
return true;
}else {
return false;
}
}
});
c.setFileSelectionMode(JFileChooser.FILES_ONLY);//设定只显示文件
2、获取数据和设置弹出框
int rVal = c.showSaveDialog(this);
if(rVal==JFileChooser.APPROVE_OPTION) {判断是否确认
File f = c.getSelectedFile();
int num = f.getName().lastIndexOf(".");
String fileName = c.getName(f);
if(num==-1) {判断扩展名有没有写,有没有写错
fileName = c.getName(f)+".xls";
}else {
String ex = f.getName().substring(num);
if(!ex.equals(".xls")) {
fileName = c.getName(f).substring(0, num)+".xls";
}
}
String local = c.getCurrentDirectory().toString()+"\\"+fileName;
File saveFile = new File(local);
try {
if (saveFile.exists()) {// 文件已经存在
int res = JOptionPane.showConfirmDialog(null, "文件已存在,是否覆盖", "提示", JOptionPane.YES_NO_OPTION);
if(res == 0) {//按下OK
FileWriter fileWriter = new FileWriter(saveFile);
fileWriter.close();
ExcelReport excelReport = new ExcelReport();自己创建的类
// excelReport.exportTable(jTable2, saveFile);//保存内容
String[] coms = {"序号","类型","支付方式","金额","时间","消费者","备注"};
excelReport.ExportTableToExcel(saveFile, "支出明细表", jTable1, coms);//导出excel
}else {
return;
}
} else {// 文件还不存在
FileWriter fileWriter = new FileWriter(saveFile);
fileWriter.close();
ExcelReport excelReport = new ExcelReport();
// excelReport.exportTable(jTable2, saveFile);//保存内容
String[] coms = {"序号","类型","支付方式","金额","时间","消费者","备注"};
excelReport.ExportTableToExcel(saveFile, "支出明细表", jTable1, coms);//导出excel
}
} catch (IOException e) {
e.printStackTrace();
}
}
3、ExcelReport 有2种,一个简单的,一个复杂点的
public class ExcelReport {
public void exportTable(JTable table, File file) throws IOException {
TableModel model = table.getModel();//简单
FileWriter out = new FileWriter(file);
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();
}
public void ExportTableToExcel(File file, String heading,JTable table,String[] columnName) {
try {//复杂
WritableWorkbook workbook = null;// 创建工作薄
workbook = Workbook.createWorkbook(file);
WritableSheet sheet = workbook.createSheet(
heading, workbook.getNumberOfSheets());// 创建工作表
//取得TABLE的行数
int rowNum = table.getRowCount();
//取得TABLE的列数
int columnNum = table.getColumnCount();
int mergeNumberOfColumns =columnNum;// 获取表格列数
fillHeading(sheet, heading, mergeNumberOfColumns);// 填写主标题
for (int k = 0; k < columnName.length; k++) {
jxl.write.Label labelN = new jxl.write.Label(k, 1,columnName[k]);
try {
sheet.addCell(labelN);
}
catch (RowsExceededException e) {
e.printStackTrace();
}
catch (WriteException e) {
e.printStackTrace();
}
}
for (int i = 0; i < columnName.length; i++) {//列
for (int j = 1; j <= rowNum; j++) {//行
String str = null;
if(table.getValueAt(j-1, i)!=null) {//为空就取值了,不然报错
str =table.getValueAt(j-1, i).toString();
}
jxl.write.Label labelN = new jxl.write.Label(i, j+1, str);
try {
sheet.addCell(labelN);
}
catch (RowsExceededException e) {
e.printStackTrace();
}
catch (WriteException e) {
e.printStackTrace();
}
}
}
//写入工作表
workbook.write();
try {
workbook.close();
int dialog = JOptionPane.showConfirmDialog(null,
"导出成功!是否打开?",
"温馨提示", JOptionPane.YES_NO_OPTION);
if (dialog == JOptionPane.YES_OPTION) {
// Runtime run = Runtime.getRuntime();
// // I make the assumption that the client has Excel and
// // the file type .XLS is associated with Excel
// // This is a simple check to find out the 操作系统!
// String lcOSName = System.getProperty("os.name").toLowerCase();
// boolean MAC_OS_X = lcOSName.startsWith("mac os x");
// if (MAC_OS_X) {
// run.exec("open " + file);
// } else {
// run.exec("cmd /c start \"\" \"" + file + "\"");
// }
Runtime.getRuntime().exec("cmd /c start \"\" \"" + file + "\"");
}
}
catch (WriteException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "导入数据前请关闭工作表");
}
catch (Exception e) {
Logger.getLogger(ExcelReport.class.getName()).log(Level.SEVERE, null, e);
JOptionPane.showMessageDialog(null, "没有进行筛选");
}
}
// 填写主标题
private void fillHeading(WritableSheet sheet, String heading, int mergeNumberOfColumns)
throws WriteException {
WritableFont font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD,
false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);// 定义字体
WritableCellFormat format = new WritableCellFormat(font);// 创建格式化对象
format.setAlignment(jxl.format.Alignment.CENTRE);// 水平居中显示
format.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直居中显示
sheet.mergeCells(0, 0, mergeNumberOfColumns - 1, 0);// 合并单元格
sheet.setRowView(0, 600);// 设置行高
sheet.addCell(new Label(0, 0, heading, format));// 填写工作表
}
}
到此结束