[java]實現導出Excel文件和XML文件 – JAVA編程語言程序開發技術文章

一、功能簡述

點擊“導出”按鈕,彈出文件選擇對話框,選擇存放路徑,填寫文件名,點擊“導出”按鈕導出界面上table中的數據到指定路徑

添加:dom4j-1.6.1.jar,用於XML

二、實現效果

2.1 界面數據

 

2.2 文件選擇對話框


2.3 導出成功後,文件內容

 

三、代碼

[java]
public class ExportFileService { 
    private static final String SAVEPATH = "D:\\";  
    private static final String BUTTONTEXT = "導出";   
    private static final String  TITLE = "導出數據";   
    public ExportFileService(){ 
         
    } 
    /**
     * 
     * @param filters  可選擇的導出類型
     * @return file[0] 文件全路徑;file[1] 導出類型
     */ 
    public static String[] exportFile(List<FileFilter> filters){   
        JFileChooser fileChooser = initEmportFile(filters); 
        int result = fileChooser.showOpenDialog(null); 
        String type = fileChooser.getFileFilter().getDescription(); 
        if (result == JFileChooser.APPROVE_OPTION) { 
            File file = fileChooser.getSelectedFile(); 
            String fn = file.getPath(); 
            String[] fileAndType = new String[2]; 
            fileAndType[0]=fn; 
            fileAndType[1]=type; 
            return fileAndType; 
        } 
        return null; 
    } 
    /**
     * 文件對話框中判斷是否覆蓋已存在文件,加入帶導入類型
     * @param filters 可選擇的導入類型
     * @return 文件選擇框
     */ 
    private static JFileChooser initEmportFile(List<FileFilter> filters) { 
        JFileChooser fileChooser = new JFileChooser(SAVEPATH) { 
            private static final long serialVersionUID = 1L; 
 
            public void approveSelection() { 
                File file; 
                String fileName = this.getSelectedFile().getAbsolutePath(); 
 
                file = new File(fileName); 
                if (file.exists()) { 
                    int copy = JOptionPane.showConfirmDialog(null, 
                            "是否要覆蓋當前文件?", "保存", JOptionPane.YES_NO_OPTION, 
                            JOptionPane.QUESTION_MESSAGE); 
                    if (copy == JOptionPane.YES_OPTION) { 
                        super.setSelectedFile(file); 
                        super.approveSelection(); 
                    } 
                } else 
                    super.approveSelection(); 
            } 
        }; 
        fileChooser.setAcceptAllFileFilterUsed(false); 
        fileChooser.setApproveButtonText(BUTTONTEXT); 
        fileChooser.setDialogTitle(TITLE); 
        for(FileFilter one :filters){ 
            fileChooser.addChoosableFileFilter( one); 
        } 
        return fileChooser; 
    } 
    /**
     * 創建新的Excel 工作簿
     * @param filename 待導出文件名稱的全路徑,不帶後綴
     * @param data 待導出數據,首個list<Object>是字段信息
     * @param sheetName 表單名稱
     * @return true 導出成功;false 導出失敗
     */ 
    @SuppressWarnings("deprecation") 
    public static boolean createExcel(String filename, List<List<Object>> data, 
            String sheetName) {  
        HSSFWorkbook workbook = null; 
        HSSFSheet sheet = null; 
        HSSFRow[] rows = null; 
        HSSFCell[][] cells = null; 
        workbook = new HSSFWorkbook(); 
        if (sheetName.trim().equals("")) { 
            sheet = workbook.createSheet("表"); 
        } else { 
            sheet = workbook.createSheet(sheetName); 
        } 
        try { 
            int row = 0; 
            int col = 0; 
            if (data.size() > 0) { 
                row = data.size(); 
                col = data.get(0).size(); 
            } 
            rows = new HSSFRow[row]; 
            cells = new HSSFCell[row][col]; 
            for (int i = 0; i < data.size(); i++) { 
                rows[i] = sheet.createRow((short) i); 
                for (int j = 0; j < data.get(i).size(); j++) { 
                    cells[i][j] = rows[i].createCell((short) j); 
                    cells[i][j].setCellType(HSSFCell.CELL_TYPE_STRING); 
                    if (data.get(i).get(j) != null 
                            && !data.get(i).get(j).toString().trim().equals("")) { 
                        cells[i][j].setCellValue(data.get(i).get(j).toString() 
                                .trim()); 
                    } else { 
                        cells[i][j].setCellValue(""); 
                    } 
                } 
            } 
            FileOutputStream fOut = new FileOutputStream(filename); 
            // 把相應的Excel 工作簿存盤 
            workbook.write(fOut); 
            fOut.flush(); 
            // 操作結束,關閉文件 
            fOut.close(); 
            return true; 
        } catch (Exception e) { 
            return false; 
        } 
    } 
    /**
     * 生成XML文件
     * @param filename 待導出文件名稱的全路徑,不帶後綴
     * @param data 待導出數據,首個list<Object>是字段信息
     * @return true 導出成功;false 導出失敗
     */ 
    public static boolean createXML(String filename, List<List<Object>> data) { 
        Document doc = DocumentHelper.createDocument(); 
        Element root = doc.addElement("root"); 
        List<Object> name = data.get(0); 
 
        for (int i = 1; i < data.size(); i++) { 
            Element row = root.addElement("row"); 
            for (int j = 0; j < name.size(); j++) { 
                Element cell = row.addElement("col" + j); 
                cell.setText(null == data.get(i).get(j) ? "" : data.get(i) 
                        .get(j).toString()); 
                cell.addAttribute("name", name.get(j).toString()); 
            } 
        } 
        try { 
            FileOutputStream fOut = new FileOutputStream(filename); 
            OutputFormat format = new OutputFormat("    ", true); 
            format.setEncoding("utf-8"); 
            // 可以把System.out改為你要的流。 
            XMLWriter xmlWriter = new XMLWriter(fOut, format); 
            xmlWriter.write(doc); 
            xmlWriter.close(); 
            return true; 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        return false; 
    } 

[java] 
/**
 * XML文件類型
 * @author rwq
 *
 */ 
public class MyFileFilterXML extends javax.swing.filechooser.FileFilter { 
     
private List<String> ext=new ArrayList<String>(); 
     
    public MyFileFilterXML(){ 
        ext.add(".XML"); 
        ext.add(".xml"); 
    } 
    public List<String> getExt() { 
        return ext; 
    } 
    public boolean accept(java.io.File pathname) { 
        String fn = pathname.getAbsolutePath().toString(); 
        if (fn.length() > 4) 
            fn = fn.substring(fn.length() – 4, fn.length()); 
        if (ext.contains(fn)|| pathname.isDirectory()) 
            return true; 
        return false; 
    } 
 
    public String getDescription() { 
        return "XML文件(*.xml)"; 
    } 

[java] 
/**
 * Excel文件類型
 * @author rwq
 *
 */ 
public class MyFileFilterExcel extends javax.swing.filechooser.FileFilter { 
     
    private List<String> ext=new ArrayList<String>(); 
     
    public MyFileFilterExcel(){ 
        ext.add(".XLS"); 
        ext.add(".xls"); 
        ext.add("xlsx"); 
        ext.add("XLSX"); 
    } 
public List<String> getExt() { 
    return ext; 

    public boolean accept(java.io.File pathname) { 
        String fn = pathname.getAbsolutePath().toString(); 
        if (fn.length() > 4){ 
            fn = fn.substring(fn.length() – 4, fn.length()); 
        } 
        if (ext.contains(fn) || pathname.isDirectory()){ 
            return true; 
        } 
        return false; 
    } 
 
    public String getDescription() { 
        return "Excel文件(*.xls,*.xlsx)"; 
    } 
 

四、調用方式
[java] 
       /**
 * 導出
 */ 
private void export() { 
    MyFileFilterExcel excelFilter = new MyFileFilterExcel(); 
    MyFileFilterXML xmlFilter = new MyFileFilterXML(); 
    List<FileFilter> filters = new ArrayList<FileFilter>(); 
    filters.add(excelFilter); 
    filters.add(xmlFilter); 
    boolean createFileRs = false; 
    String[] pathAndTypeStr = ExportFileService.exportFile(filters); 
    if(pathAndTypeStr==null){ 
        return ; 
    } 
    List<List<Object>> data = changeDataToFile(); 
    if (pathAndTypeStr[1].equals(excelFilter.getDescription())) { 
        pathAndTypeStr[0] = pathAndTypeStr[0] + ".xls"; 
        createFileRs = ExportFileService.createExcel(pathAndTypeStr[0], data, 
                viewAccountV.comboxYearAndMonth.getSelectedItem().toString()); 
    } else if (pathAndTypeStr[1].equals(xmlFilter.getDescription())) { 
        pathAndTypeStr[0] = pathAndTypeStr[0] + ".xml"; 
        createFileRs = ExportFileService.createXML(pathAndTypeStr[0], data); 
    }  
    JOptionPane.showMessageDialog(null, "文件導出" 
            + (createFileRs ? "成功" : "失敗"), "提示", 
            JOptionPane.INFORMATION_MESSAGE); 

發佈留言