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;
    }
相关推荐
Mryan20052 小时前
解决GraalVM Native Maven Plugin错误:JAVA_HOME未指向GraalVM Distribution
java·开发语言·spring boot·maven
VX_CXsjNo12 小时前
免费送源码:Java+SSM+Android Studio 基于Android Studio游戏搜索app的设计与实现 计算机毕业设计原创定制
java·spring boot·spring·游戏·eclipse·android studio·android-studio
ylfhpy2 小时前
Java面试黄金宝典33
java·开发语言·数据结构·面试·职场和发展·排序算法
乘风!3 小时前
Java导出excel,表格插入pdf附件,以及实现过程中遇见的坑
java·pdf·excel
小小鸭程序员3 小时前
Vue组件化开发深度解析:Element UI与Ant Design Vue对比实践
java·vue.js·spring·ui·elementui
南宫生3 小时前
Java迭代器【设计模式之迭代器模式】
java·学习·设计模式·kotlin·迭代器模式
seabirdssss4 小时前
通过动态获取项目的上下文路径来确保请求的 URL 兼容两种启动方式(IDEA 启动和 Tomcat 部署)下都能正确解析
java·okhttp·tomcat·intellij-idea
kill bert4 小时前
第30周Java分布式入门 消息队列 RabbitMQ
java·分布式·java-rabbitmq
穿林鸟5 小时前
Spring Boot项目信创国产化适配指南
java·spring boot·后端
此木|西贝5 小时前
【设计模式】模板方法模式
java·设计模式·模板方法模式