当前位置: 首页 > 工具软件 > Excel REPL > 使用案例 >

Java文件上传下载、导入导出excel

周威
2023-12-01

文件上传


    @PostMapping("/upload")
    public String uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = "E:\\mym/import";
            // 上传并返回新文件名称
            String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
            File desc = new File(filePath, uuid + "_" + file.getOriginalFilename());
            log.info("上传文件路径:{}", desc.getAbsolutePath());
            if (!desc.exists() && !desc.getParentFile().exists()) {
                if (!desc.getParentFile().mkdirs()) {
                    throw new RuntimeException("创建文件失败");
                }
            }
            file.transferTo(desc);
            return "success";
        } catch (Exception e) {
            log.error(e.getMessage());
            return "error";
        }
    }

文件下载

    @GetMapping("/download/{fileName}")
    public void fileDownload(@PathVariable String fileName, HttpServletResponse response) {
        try {
            String localPath = "E:\\mym/import";
            String downloadPath = localPath + File.separator + fileName;
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            log.info("下载文件路径: {}", downloadPath);
            File file = new File(downloadPath);
            if (!file.exists()) {
                throw new FileNotFoundException(downloadPath);
            }
            FileInputStream in = new FileInputStream(downloadPath);
            if (false) {
                // 在线打开 txt文件doc没成功,没研究
                URL u = new URL("file:///" + downloadPath);
                response.setContentType(u.openConnection().getContentType());
                response.setHeader("Content-Disposition", "inline; filename=" + file.getName());
            } else {
                // response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                // 本地文件
                response.setContentType("bin");
                response.addHeader("Content-Disposition", "attachment;filename="
                        + new String(file.getName().getBytes("UTF-8"), "iso8859-1"));
            }
           
            ServletOutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = in.read(b)) != -1) {
                os.write(b, 0, len);
            }
            in.close();
            os.close();
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

导入excel

依赖

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.3</version>
        </dependency>
    /**
     * 导入
     */
    @RequestMapping("/import")
    public void importExcel(MultipartFile file) {
        try {
            //从文件中读取Excel为ExcelReader
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            //转换成对应的实体类
            List<Country> countries = reader.readAll(Country.class);
            //插入到数据库
            countries.forEach(country-> countryService.save(country));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

导出excel

    @RequestMapping("/export")
    public void export(HttpServletResponse response) {
        //查询所有导出数据
        List<Country> list = countryService.list();
        // 通过工具类创建writer,默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        //自定义表格列名 给实体类对应的字段取名字
        writer.addHeaderAlias("cid", "id");
        writer.addHeaderAlias("name", "名称");
        // 合并单元格后的标题行,使用默认标题样式
        writer.merge(1, "地区表");
        // 一次性写出内容,使用默认样式,强制输出标题
        writer.write(list, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //输出表名编码
        ServletOutputStream out = null;
        try {
            String name = new String(("导出excel_" + UUID.randomUUID().toString().replace("-", "").substring(0, 6) + ".xls")
                    .getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + name);
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
        IoUtil.close(out);
    }

 类似资料: