java中excel文件下载

1、System.getProperty(user.dir) 获取的是启动项目的容器位置

2、 Files.copy(sourceFile.toPath(), destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

  • StandardCopyOption.REPLACE_EXISTING 来忽略文件已经存在的异常,如果存在就去覆盖掉它
  • StandardCopyOption.COPY_ATTRIBUTES copy文件的属性,最近修改时间,最近访问时间等信息,不仅copy文件的内容,连文件附带的属性一并复制
复制代码
    //获得要下载的excel的模板、其中mb.xlsx是模板
    String sourceFilePath = System.getProperty("user.dir") + File.separator + "mb.xlsx";
    //获得用户的当前工作目录
    String currentPath = System.getProperty("user.dir");
    //创建要生成的excel的路径
    String fileName1 = "mb" + System.currentTimeMillis();
    String destinationFilePath = currentPath + File.separator + fileName1 + ".xlsx";
    // 创建源文件和目标文件对象
    File sourceFile = new File(sourceFilePath);
    File destinationFile = new File(destinationFilePath);
    try {
        // 复制文件
        Files.copy(sourceFile.toPath(), destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        System.out.println("文件复制成功!");
    } catch (IOException e) {
        e.printStackTrace();
    }
   //填充数据
    exportRawData(list, 1, destinationFilePath);
    String fileName = "分析-" + s + "月.xlsx";
    File file = new File(destinationFilePath);
    if (file.exists()) {
        String mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        response.setContentType(mimeType);
        response.setContentLength((int) file.length());
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        try (BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(file));
             BufferedOutputStream outStream = new BufferedOutputStream(response.getOutputStream())) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }
        }
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
    Files.delete(Paths.get(destinationFilePath));
}

填充数据的代码:

java 复制代码
    boolean exportRawData(List<ImpactIndexTable> list, Integer type, String filePath) {
        String sheetName ="原始数据";
        // 要填充数据的起始行数
        int rowNum = 4;
        // 要填充数据的起始列数
        int colNum = 0;
        int rowTotal = 18;
        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fis)) {
            Sheet sheet = workbook.getSheet(sheetName);
            if (sheet == null) {
                // 如果指定的工作表不存在,可以在这里进行处理
                log.info("指定的工作表不存在!");
            }
            for (int i = 0; i < list.size(); i++) {
                // 创建并设置单元格样式
                CellStyle style = workbook.createCellStyle();
                style.setAlignment(HorizontalAlignment.CENTER);
                style.setVerticalAlignment(VerticalAlignment.CENTER);
                SXSSFWorkbook wb = new SXSSFWorkbook(-1);
                // 获取要填充的行
                Row row = sheet.getRow(rowNum + i);
                if (row == null) {
                    row = sheet.createRow(rowNum + i);
                }
                for (int n = 0; n < rowTotal; n++) {
                    Cell cell = row.createCell(colNum + n);
                    switch (n) {
                        case 0:
                            cell.setCellValue(list.get(i).getProjectName());
                            cell.setCellStyle(style);
                            break;
                        case 1:
                            cell.setCellValue(list.get(i).getHw());
                            cell.setCellStyle(style);
                            break;
                         //后续按照需要填充数据
                 
                        default:
                    }

                }
            }
            // 保存修改后的Excel文件
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                workbook.write(fos);
                log.info("数据导出成功:{}", type);
                return true;

            }
        } catch (Exception e) {
            log.error("导出错误:{}", e);
        }
        return false;
    }
相关推荐
南极Ou14 分钟前
Mybatis逆向工程详解(附源码文件)动态创建实体类、条件扩展类、Mapper接口、Mapper.xml映射文件
xml·java·mybatis
Moshow郑锴21 分钟前
IDEA为何一直无法使用超过4g内存
java·ide·intellij-idea
木头左22 分钟前
Docker容器化镜像分层原理及优化策略
java·eureka
李少兄23 分钟前
IntelliJ IDEA代码提示忽略大小写设置详解
java·ide·intellij-idea
白宇横流学长1 小时前
基于SpringBoot实现的课程答疑系统设计与实现【源码+文档】
java·spring boot·后端
积跬步至千里PRO1 小时前
在 Java 中实现一个标准 Service 接口,并通过配置动态选择具体实现类供 Controller 调用
java·简单工厂模式·解耦
chengchong_cc1 小时前
海康对接摄像头
java·vue.js
菜鸟小九1 小时前
Leetcode20 (有效的括号)
java·数据结构·算法
悟能不能悟2 小时前
讲一件Java虚拟线程
java·开发语言·oracle
fictionist2 小时前
动态 Web 开发技术入门篇
java·服务器·开发语言·笔记·学习·mysql·spring