POI動態導出Excel(動態導出前臺選中的字段)

業務場景:用戶勾選想要導出的字段
本來想着百度搜下大神封裝好的util,直接拿過來用,然而發現網上大都是寫死的(網上好多都是全表字段導出)
於是就自己寫了個通用的動態導出封裝類,前臺選中什麼字段就導出什麼字段

先看效果:

這是我數據庫表的字段
在這裏插入圖片描述
假如用戶現在只想導出name和phone這兩個字段:
直接上導出成功效果圖:
在這裏插入圖片描述

第一步:導入POM

 <!--excel導入導出 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.11-beta2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.11-beta2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.11-beta2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-excelant</artifactId>
            <version>3.11-beta2</version>
        </dependency>

第二部:導入我的util類(註釋寫的很明白啦)

 /**
     * @param title  表格的名字
     * @param heards 前臺選中要導出的字段
     * @param list   查詢數據庫返回所有字段的結果
     * @param out    輸出流
     * @throws Exception
     */
    public static void exportUtil(String title, String[] heards, List<?> list, OutputStream out) throws Exception {
        // 創建excel工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 創建excel表
        HSSFSheet sheet = workbook.createSheet(title);
        // 創建標題行
        HSSFRow titleRow = sheet.createRow(0);
        // 標題行寫內容
        for (int i = 0; i < heards.length; i++) {
            String s = heards[i];
            HSSFCell cell = titleRow.createCell(i);
            cell.setCellValue(s);
        }

        // 數據行,從1行開始,共list.size行
        for (int i = 1; i <= list.size(); i++) {
            // 創建行
            HSSFRow listRow = sheet.createRow(i);
            // 數據行單元格,從0開始,共heards.length列
            for (int j = 0; j < heards.length; j++) {
                // 創建數據單元格
                HSSFCell listCell = listRow.createCell(j);
                // 通過反射的方式,將heards元素通過字符串拼接的方式,拼接出實體類相對應的get方法;
                String methodName = "get" + heards[j].substring(0, 1).toUpperCase() + heards[j].substring(1);

                try {
                    // 通過反射拿到類對象,再獲取類對象的額methodName這個方法
                    Method declaredMethod = Student.class.getDeclaredMethod(methodName, null);
                    // 通過invoke提交對象,執行declaredMethod這個方法
                    // 從List<Student>集合中取出list.get(i - 1)的methodName屬性的值;
                    Object result = declaredMethod.invoke(list.get(i - 1));

                    //判斷返回值的類型
                    if (result instanceof Date) {
                        //填寫日期格式內容
                        HSSFDataFormat dataFormat = workbook.createDataFormat();
                        short format = dataFormat.getFormat("yyyy年MM月dd日");
                        HSSFCellStyle cellStyle = workbook.createCellStyle();
                        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                        cellStyle.setDataFormat(format);
                        listCell.setCellStyle(cellStyle);
                    } else {
                        //設置內容
                        listCell.setCellValue(result.toString());
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }

            }
        }

         /*// 設置響應頭
        response.setContentType("application/vnd.ms-excel");
        String fileName = "用戶自定義信息表.xls";
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.addHeader("Content-Disposition", "attachment;" + fileName);
        workbook.write(response.getOutputStream());*/
        try {
            workbook.write(out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

第三部:直接調用測試

 @RequestMapping("/exports")
    public Map exports(HttpServletResponse response) throws Exception {
        Map map = new HashMap();
        String[] heards = {"id", "name"};
        List<Student> list = exportService.export();
        exportUtil("zsp", heards, list, new FileOutputStream("E:/test.xls"));
        return map;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章