Java combat the housekeeper billing system (6) - Import and export functions to achieve

This clause Overview

This section will enable users to export records of income and expenditure to excel table, you can also import from housekeeper to excel in the accounting system.

 

Export

Export user records to excel table, do not need to implement export interface functions, it is an event triggered by a menu item, so the export function logic code written in exportMenuItemEvent () method can be.

    /**
     * “导出”菜单项的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void exportMenuItemEvent(ActionEvent actionEvent) {
        String exportPath = null;
        //实例化文件选择器
        FileChooser fileChooser = new FileChooser();
        //打开保存文件选择框
        fileChooser.setInitialFileName("Excel");
        File result = fileChooser.showSaveDialog(null);
        if(result!=null){
            exportPath = result.getAbsolutePath();
            //excel表格表头
            String[] title = {"序号", "类型", "金额", "分类", "备注", "日期"};
            // 获取当前用户的支出记录
            List<Record> recordList = recordDao.selectByUserId(Session.getUser().getUserId());
            // 将支出记录转换成二维数组
            String[][] tableData = new String[recordList.size()][6];
            int j = 0;
            for (Record record : recordList) {
                tableData[j][0] = String.valueOf(record.getRecordId());
                tableData[j][1] = record.getRecordType();
                tableData[j][2] = Float.toString(record.getRecordMoney());
                tableData[j][3] = record.getRecordClassification();
                tableData[j][4] = record.getRecordMemo();
                tableData[j][5] = record.getRecordDate();
                j++;
            }
            //导出路径
            String exportExcelFilePath = SimpleTools.exportExcel(title, tableData, exportPath);
            if (new File(exportExcelFilePath).exists()) {
                SimpleTools.informationDialog(Alert.AlertType.INFORMATION, "提示", "信息", "导出excel成功!");
            } else {
                SimpleTools.informationDialog(Alert.AlertType.ERROR, "提示", "错误", "导出excel失败!");
            }
        }
    }

Obtained by FileChooser file selector you want to save the file path and method to get all the income and expenses recorded by the user RecordDao class selectByUserId (), then call exportExcel SimpleTools class () method writes to excel in. Since the three parameters exportExcel method first argument is the data header is a one-dimensional array; second parameter refers to the table of contents, a two-dimensional array, it is necessary to convert the content into a two-dimensional array selectByUserId to obtain use; third parameter refers excel file export path.

Run the program, test and export functions:

Open excel file to view the records exported.

img

 

Import function

Import feature is also handled by an event triggered by menu item introduced in importMenuItemEvent MainPageController.java will change the code to the following method:

    /**
     * “导入”菜单项的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void importMenuItemEvent(ActionEvent actionEvent) {
        //实例化文件选择器
        FileChooser fileChooser = new FileChooser();
        //设置默认文件过滤器
        fileChooser.setSelectedExtensionFilter(new FileChooser.ExtensionFilter("excel(*.xls)", "xls", "xlsx"));
        //打开文件选择框,并得到选中的文件
        File result = fileChooser.showOpenDialog(null);
        if(result!=null){
            // 获取绝对路径
            String importPath = result.getAbsolutePath();
            try {
                //读取excel表内容(不包括表头)
                String[][] content = SimpleTools.readExcelContentArray(new FileInputStream(importPath));
                boolean isSuccess = false;
                for (int i = 0; i < content.length; i++) {
                    Record record = new Record();
                    record.setUserId(Session.getUser().getUserId());
                    record.setRecordType(content[i][1]);
                    record.setRecordMoney(Float.parseFloat(content[i][2]));
                    record.setRecordClassification(content[i][3]);
                    record.setRecordMemo(content[i][4]);
                    record.setRecordDate(content[i][5]);
                    //添加数据到数据库
                    isSuccess = recordDao.addRecord(record);
                }
                // 判断是否导入成功
                if (isSuccess) {
                    SimpleTools.informationDialog(Alert.AlertType.INFORMATION, "提示", "信息", "导入excel数据成功");
                    // 刷新界面显示的数据
                    initialize();
                } else {
                    SimpleTools.informationDialog(Alert.AlertType.ERROR, "提示", "错误", "导入excel数据失败");
                }
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }
        }
    }

Use FileChooser control to open Explorer to select the file you want to import excel and read its absolute path, and then call SimpleTools class readExcelContentArray () method to read the contents of excel sheet, but do not read the contents of the header, reading results is a two-dimensional array, which loops through the package and inserted into the record class table record into the database, the number of rows to insert the number of records, after the call initialization function successfully introduced initialize () refresh of the screen data.

Run the program, test function:

To import the excel test data:

Import successful tips:

Red box that is recorded as follows imported data:

Recording data on import and export functions are related to the use of poi package, as defined in SimpleTools methods in the class, if interested in how to achieve specific, can view the specific code of the calling method. If you are interested in reading and writing, then you can excel on their own to find information for their own use encapsulation methods on the Internet.

 

 

Searchable public micro-channel number [ Java example program ] or scan the Fanger Wei code number to get more public attention.

Note: Reply to [the public number background 20200319 ] can get the source code of this chapter.

Published 500 original articles · won praise 77 · views 160 000 +

Guess you like

Origin blog.csdn.net/cnds123321/article/details/104275273