JAVA POI導出excel

1.引入maven 依賴java

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>${poi.version}</version>
        </dependency>

  

2.工具類apache

public class ExcelUtils {
    /**
     * @param response
     * @param fileName excel文件名
     * @param headMap  表頭map
     * @param dataList 表格數據
     */
    public static void exportXlsx(HttpServletResponse response, String fileName,
                                  Map<String, String> headMap, List<Map<String, Object>> dataList) {

        Workbook workbook = exportXlsx(fileName, headMap, dataList);
        response.setContentType("application/binary;charset=ISO8859_1");

        OutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();
            String fn = new String(fileName.getBytes(), "ISO8859_1");
            response.setHeader("Content-disposition", "attachment; filename=" + fn + ".xlsx");
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 導出數據
     *
     * @param headMap
     * @param dataList
     */
    public static Workbook exportXlsx(String sheetName, Map<String, String> headMap, List<Map<String, Object>> dataList) {

        Workbook workbook = new XSSFWorkbook();

        Sheet sheet = workbook.createSheet(sheetName);


        int rowIndex = 0, columnIndex = 0;
        Set<String> keys = headMap.keySet();

        //表頭
        Row row = sheet.createRow(rowIndex++);
        for (String key : keys) {
            Cell cell = row.createCell(columnIndex++);
            cell.setCellValue(headMap.get(key));
        }

        //內容
        if (dataList != null && !dataList.isEmpty()) {
            for (Map<String, Object> map : dataList) {
                row = sheet.createRow(rowIndex++);
                columnIndex = 0;
                for (String key : keys) {
                    Cell cell = row.createCell(columnIndex++);
                    setCellValue(cell, map.get(key));
                }
            }
        }

        return workbook;
    }

    private static void setCellValue(Cell cell, Object obj) {
        if (obj == null) {
            return;
        }
        if (obj instanceof String) {
            cell.setCellValue((String) obj);
        } else if (obj instanceof Date) {
            Date date = (Date) obj;
            if (date != null) {
                cell.setCellValue(DateUtils.dfDateTime.format(date));
            }
        } else if (obj instanceof Calendar) {
            Calendar calendar = (Calendar) obj;
            if (calendar != null) {
                cell.setCellValue(DateUtils.dfDateTime.format(calendar.getTime()));
            }
        } else if (obj instanceof Timestamp) {
            Timestamp timestamp = (Timestamp) obj;
            if (timestamp != null) {
                cell.setCellValue(DateUtils.dfDateTime.format(new Date(timestamp.getTime())));
            }
        } else if (obj instanceof Double) {
            cell.setCellValue((Double) obj);
        } else {
            cell.setCellValue(obj.toString());
        }
    }
}

  3.controller導出用戶數據app

@RequestMapping("/export")
    public String export(String username, HttpServletRequest request, HttpServletResponse repsonse) {
        //查詢用戶數據
        UserQueryDTO queryDTO = new UserQueryDTO() {{
            setUsername(username);
        }};
        List<CmsUser> userList = userService.findUser(queryDTO);

        //表頭
        Map<String, String> headNameMap = new LinkedHashMap<String, String>();
        headNameMap.put("userId", "ID");
        headNameMap.put("roleName", "角色");
        headNameMap.put("userName", "帳號");
        headNameMap.put("realName", "姓名");
        headNameMap.put("mobile", "電話號碼");
        headNameMap.put("createDate", "建立時間");
        headNameMap.put("status", "狀態");

        //表格數據
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (userList != null && userList.size() > 0) {
            for (CmsUser user : userList) {
                String statusName = "正常";
                if (StringUtils.isNotBlank(user.getDeleteFlag()) && user.getDeleteFlag().equals(ConstantHelper.DELETE_FLAG_DELETED)) {
                    statusName = "刪除";
                }

                String createDate = "";
                if (user.getCreateDate() != null) {
                    createDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(user.getCreateDate());
                }

                String roleName = "";
                Set<CmsRole> roleSet = roleService.findByUserId(user.getUserId());
                if (roleSet != null && roleSet.size() > 0) {
                    for (CmsRole r : roleSet) {
                        roleName += r.getName() + " ";
                    }
                }

                Map<String, Object> map = new HashMap<String, Object>();
                map.put("userId", user.getUserId());
                map.put("roleName", roleName);
                map.put("userName", user.getUsername());
                map.put("realName", user.getRealName());
                map.put("mobile", user.getMobile());
                map.put("createDate", createDate);
                map.put("status", statusName);
                list.add(map);
            }
        }

        ExcelUtils.exportXlsx(repsonse, "用戶", headNameMap, list);
        return null;
    }
相關文章
相關標籤/搜索