上传 Excel 文件进行数据库比对--增加导出功能

一、确认pom.xml中存在poi依赖

复制代码
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.5</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.5</version>
</dependency>

二、在FileController中增加导出方法

复制代码
@GetMapping("/export-results")
public ResponseEntity<byte[]> exportResultsToExcel(HttpSession session) {
    try {
        // ✅ 改为 UserInfo
        @SuppressWarnings("unchecked")
        List<UserInfo> results = (List<UserInfo>) session.getAttribute("matchResults");

        if (results == null || results.isEmpty()) {
            return ResponseEntity.notFound().build();
        }

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("身份证比对结果");

        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("ID");
        header.createCell(1).setCellValue("姓名");
        header.createCell(2).setCellValue("身份证号码");

        for (int i = 0; i < results.size(); i++) {
            UserInfo user = results.get(i); // ← 这里是 UserInfo
            Row row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(user.getId() != null ? user.getId() : 0L);
            row.createCell(1).setCellValue(user.getName() != null ? user.getName() : "");
            row.createCell(2).setCellValue(user.getIdCard() != null ? user.getIdCard() : "");
        }

        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);
        sheet.autoSizeColumn(2);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        workbook.write(out);
        workbook.close();

        String timestamp = java.time.LocalDateTime.now()
                .format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String filename = "身份证比对结果_" + timestamp + ".xlsx";
        String encodedFilename = java.net.URLEncoder.encode(filename, "UTF-8")
                .replaceAll("\\+", "%20");

        return ResponseEntity.ok()
                .header(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + encodedFilename + "\"; filename*=UTF-8''" + encodedFilename)
                .header(org.springframework.http.HttpHeaders.CONTENT_TYPE,
                        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                .body(out.toByteArray());

    } catch (Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

三、在你原来的 /upload POST 处理方法中,将 results 存入 session

复制代码
 @PostMapping("/upload")
    public String handleUpload(@RequestParam("file") MultipartFile file,
                               Model model,
                               HttpSession session) { // <-- 添加 HttpSession 参数

        // 清除之前的结果(可选,但推荐)
        session.removeAttribute("matchResults");

        if (file.isEmpty()) {
            model.addAttribute("error", "请选择一个 Excel 文件");
            return "upload";
        }

        try {
            List<UserInfo> matchedUsers = excelService.processExcel(file);

            // ✅ 将结果保存到 session,供导出使用
            session.setAttribute("matchResults", matchedUsers);

            model.addAttribute("results", matchedUsers);
            model.addAttribute("count", matchedUsers.size());

        } catch (IOException e) {
            model.addAttribute("error", "文件读取失败:" + e.getMessage());
        } catch (IllegalArgumentException e) {
            model.addAttribute("error", "Excel 格式错误:" + e.getMessage());
        }

        return "upload";
    }

四、清除 session

复制代码
@GetMapping("/clear")
public String clearSession(HttpSession session) {
    session.removeAttribute("matchResults");
    return "redirect:/upload";
}

五、在 HTML 页面添加"导出 Excel"按钮,清空按钮方法修改为/clear

复制代码
<!-- 清空按钮 -->
<div class="actions">
    <button type="button" onclick="window.location.href='/clear'">清空记录</button>
</div>
<!-- 导出按钮 -->
<button type="button" onclick="window.location.href='/export-results'"
        style="margin-left: 10px; background-color: #4CAF50; color: white;">
    📥 导出 Excel
</button>
相关推荐
数据组小组22 分钟前
免费数据库管理工具深度横评:NineData 社区版、Bytebase 社区版、Archery,2026 年开发者该选哪个?
数据库·测试·数据库管理工具·数据复制·迁移工具·ninedata社区版·naivicat平替
悟空聊架构7 小时前
基于KaiwuDB在游乐场“刷卡+投币”双模消费系统中的落地实践
数据库·后端·架构
IvorySQL7 小时前
PostgreSQL 技术日报 (3月4日)|硬核干货 + 内核暗流一网打尽
数据库·postgresql·开源
进击的丸子10 小时前
虹软人脸服务器版SDK(Linux/ARM Pro)多线程调用及性能优化
linux·数据库·后端
NineData1 天前
NineData智能数据管理平台新功能发布|2026年1-2月
数据库·sql·数据分析
IvorySQL1 天前
双星闪耀温哥华:IvorySQL 社区两项议题入选 PGConf.dev 2026
数据库·postgresql·开源
ma_king1 天前
入门 java 和 数据库
java·数据库·后端
jiayou641 天前
KingbaseES 实战:审计追踪配置与运维实践
数据库
NineData2 天前
NineData 迁移评估功能正式上线
数据库·dba
NineData2 天前
数据库迁移总踩坑?用 NineData 迁移评估,提前识别所有兼容性风险
数据库·程序员·云计算