Excel数据的导出返回url给前端(靠谱)

package com.xmyq.pojo;


import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Value;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import java.util.Date;


@Data
@TableName("report")
@AllArgsConstructor
@NoArgsConstructor
public class Report {

    private static final long serialVersionUID = 1L;

    @TableId(type = IdType.AUTO)
    @GeneratedValue
    /**
     * id
     */
    @Column(name = "rep_id")
    private Long repId;

    /**
     * 报告编号
     */
    @ExcelProperty(value = "报告编号")
    @Column(name = "rep_number")
    private String repNumber;

    /**
     * 关联的合同id
     */
    @ExcelProperty(value = "关联的合同id")
    @Column(name = "rep_order")
    private Long repOrder;

    /**
     * 生成时间
     */
    @ExcelProperty(value = "生成时间")
    @Column(name = "rep_time")

    private Date repTime;

    /**
     * 更新时间
     */
    @ExcelProperty(value = "更新时间")
    @Column(name = "update_time")
    private Date updateTime;

    /**
     * 外键id
     */
    @Column(name = "rep_fk_id")
    @ExcelProperty(value = "外键id")
    private String repFkId;

    /**
     * pdf地址
     */
    @Column(name = "rep_pdf_url")
    @ExcelProperty(value = "pdf地址")
    private String repPdfUrl;

    /**
     * 创建者
     */
    @Column(name = "create_by")
    @ExcelProperty(value = "创建者")
    private Long createBy;

    /**
     * 更新者
     */
    @Column(name = "update_by")
    @ExcelProperty(value = "更新者")
    private Long updateBy;

    /**
     * 文件路径
     */
    @Column(name = "fil_dir")
    @ExcelProperty(value = "文件路径")
    private String filDir;

    /**
     * 文件名称
     */
    @ExcelProperty(value = "文件名称")
    @Column(name = "fil_name")
    private String filName;

    /**
     * 报告状态
     */
    @ExcelProperty(value = "报告状态")
    @Column(name = "rep_status")
    private Integer repStatus;

    /**
     * 审核意见
     */
    @Column(name = "rep_audit_opinion")
    @ExcelProperty(value = "审核意见")
    private String repAuditOpinion;

    /**
     * 审批意见
     */
    @Column(name = "rep_approval_opinion")
    @ExcelProperty(value = "审批意见")
    private String repApprovalOpinion;

    /**
     * 用户名
     */
    @Column(name = "user_name")
    @ExcelProperty(value = "用户名")
    private String userName;

    /**
     * 状态
     */
    @Column(name = "status")
    @ExcelProperty(value = "状态")
    private int status;

    /**
     * 创建时间
     */
    @Column(name = "create_time")
    @ExcelProperty(value = "创建时间")
    private Date createTime;


}
package com.xmyq.controller;

import com.xmyq.service.ReportService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;

@RestController
@RequestMapping("/reports")
public class ReportController {

    @Autowired
    private ReportService reportService;

    @GetMapping("/export/excel")
    public String exportExcel(HttpServletResponse response) {
        return reportService.exportExcel(response);
    }

    @RequestMapping("download")
    public void download(@Param("source") String source, HttpServletRequest request, HttpServletResponse response) throws Exception{
        File file = new File(source);
        if (file == null || !file.exists()) {
            throw new FileNotFoundException("请求的文件不存在");
        }
        OutputStream out = null;
        try {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            String agent = (String)request.getHeader("USER-AGENT");
            String fileName = file.getName();
            if(agent != null && agent.indexOf("MSIE") == -1) {
// FF
                String enableFileName = "=?UTF-8?B?" + (new String(Base64.getEncoder().encode(fileName.getBytes("UTF-8")))) + "?=";
                response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName); }
            else {
// IE
                String enableFileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
                response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName);
            }
//			response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
            out = response.getOutputStream();
            out.write(org.apache.commons.io.FileUtils.readFileToByteArray(file));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
package com.xmyq.service.impl;

import com.xmyq.mapper.ReportMapper;
import com.xmyq.pojo.Report;
import com.xmyq.service.ReportService;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;


    public String exportExcel(HttpServletResponse response) {
        //查询数据库获取营业数据
        List<Report> reportList = reportMapper.excelBusinessData();
        try {
        //通过poi将数据写入到excel文件中
            // 读取模板文件
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/template.xlsx");

            XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);
            XSSFSheet sheet1=  excel.getSheet("Sheet1");
            if (sheet1 == null) {
                throw new RuntimeException("模板文件中没有名为'Sheet1'的工作表");
            }
            // 填充数据
            int rowNum = 1;
            for (Report report : reportList) {
                XSSFRow row = sheet1.createRow(rowNum++);
                row.createCell(0).setCellValue(report.getFilName());
                row.createCell(1).setCellValue(report.getRepOrder());
                row.createCell(2).setCellValue(report.getRepPdfUrl());
                row.createCell(3).setCellValue(report.getStatus());
                row.createCell(4).setCellValue(report.getUserName());
            }

            // 生成文件名
            String fileName = "exportedFile.xlsx";
            String filePath =  fileName;

            // 写入到文件
            try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
                excel.write(fileOut);
            }

            // 上传文件到Web服务器
            // 这里需要根据具体的Web服务器进行文件上传操作,并获取上传后的URL地址
            String fileUrl = "  http://localhost:9999/file/download?source=" + fileName;
            http://localhost:9999/file/download?source=
            return fileUrl; // 返回文件URL地址
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}




在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
这是模版存放位置
在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,可以使用Apache POI库来导出Excel文件并将其返回前端进行下载。 首先,我们需要在pom.xml文件中添加Apache POI的依赖项: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 接下来,创建一个Excel导出的处理器方法。可以在Controller中创建一个方法,该方法使用`@RequestMapping`或`@GetMapping`注解来指定URL路径和HTTP请求方法。在该方法中,可以使用Apache POI来创建和填充Excel工作簿。例如,以下代码演示了如何在Excel中创建并填充一个简单的表格: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; @RequestMapping("/export") public ResponseEntity<Resource> exportExcel() throws IOException { // 创建Excel工作簿 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); // 填充数据 Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("姓名"); headerRow.createCell(1).setCellValue("年龄"); Row dataRow = sheet.createRow(1); dataRow.createCell(0).setCellValue("张三"); dataRow.createCell(1).setCellValue(25); // 将工作簿转换为字节数组 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); byte[] excelBytes = outputStream.toByteArray(); // 创建HTTP响应体,并设置文件下载的相关头信息 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", "data.xlsx"); // 返回带有Excel文件的响应实体 return new ResponseEntity<>(new ByteArrayResource(excelBytes), headers, HttpStatus.OK); } ``` 在上面的代码中,我们创建了一个简单的Excel表格,并将其转换为字节数组形式。然后,我们创建了一个包含Excel文件的响应实体,并设置了HTTP响应头以指定文件下载的相关信息,例如文件名和Content-Type。最后,我们将响应实体返回前端进行下载。 以上是一个简单的示例,你可以根据实际需求来创建更复杂的Excel导出

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值