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;
    }
相关推荐
yngsqq2 小时前
c# —— StringBuilder 类
java·开发语言
星星点点洲3 小时前
【操作幂等和数据一致性】保障业务在MySQL和COS对象存储的一致
java·mysql
xiaolingting3 小时前
JVM层面的JAVA类和实例(Klass-OOP)
java·jvm·oop·klass·instanceklass·class对象
风口上的猪20153 小时前
thingboard告警信息格式美化
java·服务器·前端
追光少年33224 小时前
迭代器模式
java·迭代器模式
超爱吃士力架5 小时前
MySQL 中的回表是什么?
java·后端·面试
扣丁梦想家5 小时前
设计模式教程:装饰器模式(Decorator Pattern)
java·前端·装饰器模式
drebander5 小时前
Maven 构建中的安全性与合规性检查
java·maven
drebander5 小时前
Maven 与 Kubernetes 部署:构建和部署到 Kubernetes 环境中
java·kubernetes·maven
王会举5 小时前
DeepSeek模型集成到java中使用(阿里云版)超简单版
java·阿里云·deepseek