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));
}

 填充数据的代码:

    boolean exportRawData(List 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;
    }

你可能感兴趣的:(java)