六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 36|回复: 0

JTable 导出 Excel 利用 jxl.jar

[复制链接]

升级  32%

26

主题

26

主题

26

主题

秀才

Rank: 2

积分
98
 楼主| 发表于 2013-1-15 02:40:14 | 显示全部楼层 |阅读模式
/* * 注明出处!!  *QQ: 409323911   */package com.db.report;import java.io.File;import java.io.FileNotFoundException;import java.util.logging.Level;import java.util.logging.Logger;import javax.swing.JOptionPane;import javax.swing.JTable;import jxl.Workbook;import jxl.format.Alignment;import jxl.format.Colour;import jxl.format.UnderlineStyle;import jxl.format.VerticalAlignment;import jxl.write.Label;import jxl.write.WritableCellFormat;import jxl.write.WritableFont;import jxl.write.WritableSheet;import jxl.write.WritableWorkbook;import jxl.write.WriteException;import jxl.write.biff.RowsExceededException;/** * * @author Administrator */public class ExportTableToExcel  {    public ExportTableToExcel(File file, String heading,String inscribe,JTable table,String[] columnName) {        try {            WritableWorkbook workbook = null;// 创建工作薄            if (file.exists()) {// 文件已经存在                workbook = Workbook.createWorkbook(file, Workbook.getWorkbook(file));            } else {// 文件还不存在                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);// 填写主标题            fillInscribe(sheet, inscribe, mergeNumberOfColumns,rowNum);// 填写落款//             fillSubheading(sheet, subheading, mergeNumberOfColumns);// 填写副标题           //             fillColumnName(sheet);// 填写列名//             fillCell(sheet);// 填写数据                        for (int k = 0; k < columnNum; k++) {              jxl.write.Label labelN = new jxl.write.Label(k, 2,columnName[k]);              try {                sheet.addCell(labelN);              }              catch (RowsExceededException e) {                // TODO Auto-generated catch block                e.printStackTrace();              }              catch (WriteException e) {                // TODO Auto-generated catch block                e.printStackTrace();              }            }            for (int i = 0; i < columnNum; i++) {//列              for (int j = 1; j <= rowNum; j++) {//                String str = null;                str =table.getValueAt(j-1, i).toString();                jxl.write.Label labelN = new jxl.write.Label(i, j, 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(ExportTableToExcel.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(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));// 填写工作表    }    //填写落款    private void fillInscribe(WritableSheet sheet, String inscribe, int mergeNumberOfColumns, int rowNum)            throws WriteException {        WritableFont font = new WritableFont(WritableFont.ARIAL, 11, WritableFont.NO_BOLD,                false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);// 定义字体        WritableCellFormat format = new WritableCellFormat(font);// 定义格式化对象        format.setAlignment(Alignment.LEFT);// 水平居中显示        sheet.mergeCells(0, rowNum+2, mergeNumberOfColumns - 1, rowNum+2);// 合并单元格        sheet.addCell(new Label(0,rowNum+2, inscribe, format));// 填写工作表    }    //=====================================填写副标题=====================================//    private void fillSubheading(WritableSheet sheet, String subheading, int mergeNumberOfColumns)//            throws WriteException {//        WritableFont font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.NO_BOLD,//                false, UnderlineStyle.NO_UNDERLINE, Colour.RED);// 定义字体////        WritableCellFormat format = new WritableCellFormat(font);// 定义格式化对象////        format.setAlignment(Alignment.CENTRE);// 水平居中显示////        format.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直居中显示////      //  sheet.mergeCells(0, 1, mergeNumberOfColumns - 1, 1);// 合并单元格////        sheet.setRowView(1, 400);// 设置行高////        sheet.addCell(new Label(0, 1, subheading, format));// 填写工作表////    }    //=====================================填写列名=====================================//    private void fillColumnName(WritableSheet sheet) throws WriteException {//        WritableFont font = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD,//                false, UnderlineStyle.NO_UNDERLINE, Colour.RED);// 定义字体////        WritableCellFormat format = new WritableCellFormat(font);// 定义格式化对象////        format.setAlignment(Alignment.CENTRE);// 水平居中显示////        sheet.setColumnView(0, 15);// 设置列宽////        //填写工作表//        for (int column = 0; column < columnName.size(); column++) {//            sheet.addCell(new Label(column, 3, columnName.get(column), format));//        }//    }////    //填写数据//    private void fillCell(WritableSheet sheet) throws WriteException {//        WritableFont font = new WritableFont(WritableFont.ARIAL, 12, WritableFont.NO_BOLD,//                false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);// 定义字体////        WritableCellFormat format = new WritableCellFormat(font);// 定义格式化对象////        format.setAlignment(Alignment.CENTRE);// 水平居中显示////        //填写工作表//        for (int row = 0; row < tableData.size(); row++) {//            Vector rowData = tableData.get(row);//            for (int column = 0; column < rowData.size(); column++) {//                sheet.addCell(new Label(column, row + 4, rowData.get(column).toString(), format));//            }//        }//    }} 调用上面导出excel类:
button.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {File selectedFile = getSelectedFile(".xls");if (selectedFile != null) {String[] columnName = { "编号", " 学号", "姓名", "班级", "性别","生日", "身份证", "年龄", "学历", "专业", "联系方式", "就业城市","学生状态", "备注" };String today = new SimpleDateFormat("yyyy年MM月dd日").format(new Date());String inscribe = "填表人:                                                                        填表日期:"+ today; // 页脚new ExportTableToExcel(selectedFile, fileName, inscribe,table, columnName);}}}); private File getSelectedFile(final String type) {String name = fileName;JFileChooser pathChooser = new JFileChooser();pathChooser.setFileFilter(new FileFilter() {@Overridepublic boolean accept(File f) {if (f.isDirectory()) {return true;} else {if (f.getName().toLowerCase().endsWith(type)) {return true;} else {return false;}}}@Overridepublic String getDescription() {return "文件格式(" + type + ")";}});pathChooser.setSelectedFile(new File(name + type));int showSaveDialog = pathChooser.showSaveDialog(this);if (showSaveDialog == JFileChooser.APPROVE_OPTION) {return pathChooser.getSelectedFile();} else {return null;}}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表