一、功能简述
点击“导出”按钮,弹出文件选择对话框,选择存放路径,填写文件名,点击“导出”按钮导出界面上table中的数据到指定路径
添加:dom4j-1.6.1.jar,用于XML
二、实现效果
2.1 界面数据
2.2 文件选择对话框
2.3 导出成功后,文件内容
三、代码
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; } }
/** * 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)"; } }
/** * 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)"; } }
四、调用方式
/** * 导出 */ 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); }
说明:
调用处的数据转换不是重点,省略
代码留存,方便使用