写excel文件流给前端,记录使用

方法:

@Override
public void generateExcel(HttpServletResponse response) {
        // 设置当前的xlsx最大长度为1000行
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        // 设置文件后缀
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fn = "xlsx" + sdf.format(new Date()).toString() + ".xlsx";
        //设置表格名称
        SXSSFSheet sheet = wb.createSheet("sheet1");
        // 设置默认的宽度为30个字符
        sheet.setDefaultColumnWidth(30);
        SXSSFRow row = sheet.createRow(0);
        //目前写死
        List<String> biaoTou = new ArrayList<>(Arrays.asList("服务内容", "服务类型", "城市", "地区", "业主"
                , "服务时间", "服务地址", "服务星级", "服务评价", "状态", "图片1", "图片2", "图片3", "图片4", "图片5", "图片6"));
        // 遍历插入表头
        for (int i = 0; i < 16; i++) {
            //15列
            SXSSFCell cell = row.createCell(i);
            cell.setCellValue(biaoTou.get(i));
        }
        ServiceTrendQuery serviceTrendQuery=new ServiceTrendQuery();
        List<ServiceTrend> serviceTrendVOS = serviceTrendMapper.commonQuery(serviceTrendQuery);
        SXSSFRow row2;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for(int j = 1; j <= serviceTrendVOS.size();j++){
            row2 = sheet.createRow(j);
            SXSSFCell cell1 = row2.createCell(0);
            cell1.setCellValue(serviceTrendVOS.get(j - 1).getServiceContent());
            SXSSFCell cell2 = row2.createCell(1);
            cell2.setCellValue(serviceTrendVOS.get(j - 1).getServiceType());
            SXSSFCell cell3 = row2.createCell(2);
            cell3.setCellValue(serviceTrendVOS.get(j - 1).getCity());
            SXSSFCell cell4 = row2.createCell(3);
            cell4.setCellValue(serviceTrendVOS.get(j - 1).getCounty());
            SXSSFCell cell5 = row2.createCell(4);
            cell5.setCellValue(serviceTrendVOS.get(j - 1).getOwner());
            SXSSFCell cell6 = row2.createCell(5);
            cell6.setCellValue(simpleDateFormat.format(serviceTrendVOS.get(j - 1).getServiceTime()));
            SXSSFCell cell7 = row2.createCell(6);
            cell7.setCellValue(serviceTrendVOS.get(j - 1).getServiceAddress());
            SXSSFCell cell8 = row2.createCell(7);
            cell8.setCellValue(serviceTrendVOS.get(j - 1).getServiceLevel());
            SXSSFCell cell9 = row2.createCell(8);
            cell9.setCellValue(serviceTrendVOS.get(j - 1).getServiceComment());
            SXSSFCell cell10 = row2.createCell(9);
            cell10.setCellValue(serviceTrendVOS.get(j - 1).getStatus() == 1 ? "待评价" : "已评价");
            SXSSFCell cell11 = row2.createCell(10);
            cell11.setCellValue(serviceTrendVOS.get(j - 1).getNormalPic1());
            SXSSFCell cell12 = row2.createCell(11);
            cell12.setCellValue(serviceTrendVOS.get(j - 1).getNormalPic2());
            SXSSFCell cell13 = row2.createCell(12);
            cell13.setCellValue(serviceTrendVOS.get(j - 1).getNormalPic3());
            SXSSFCell cell14 = row2.createCell(13);
            cell14.setCellValue(serviceTrendVOS.get(j - 1).getNormalPic4());
            SXSSFCell cell15 = row2.createCell(14);
            cell15.setCellValue(serviceTrendVOS.get(j - 1).getNormalPic5());
            SXSSFCell cell16 = row2.createCell(15);
            cell16.setCellValue(serviceTrendVOS.get(j - 1).getNormalPic6());

        }
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
        wb.write(byteArrayOutputStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    byte[] excelBytes = byteArrayOutputStream.toByteArray();
  CommonResponse<Object> commonResponse = CommonResponse.builder()
            .withVersion("1.0") // 设置版本号
            .withCode("0")      // 设置成功的代码
            .withMessage("Success") // 设置消息
            .withFlag(0) // 设置加密标志,如果需要的话
            .withBody(excelBytes)// 将Excel文件的字节数组作为body
            .build();

    ObjectMapper objectMapper = new ObjectMapper();
    String jsonResponse;
    try {
      jsonResponse = objectMapper.writeValueAsString(commonResponse);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
    try (PrintWriter writer = response.getWriter()) {
        writer.write(jsonResponse);
    } catch (IOException e) {
        throw new RuntimeException(e);}

CommonResponse.java:

/**
 * @file: CommonResponse.java
 * @author: liang_xiaojian
 * @date: 2020/8/26 14:36
 * @copyright: 2020-2023 www.bosssoft.com.cn Inc. All rights reserved.
 */
package com.sd365.common.core.common.api;

import org.springframework.util.StringUtils;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * @class CommonResponse
 * @classdesc  通过该类实施统一应答,统一应答参考 DefaultUnifyResponseBodyAware
 * @author liang_xiaojian
 * @date 2020/8/26  14:36
 * @version 1.0.0
 * @see
 * @since
 */
public class CommonResponse<T> implements Serializable {

    private static final long serialVersionUID = -6372561804247815227L;

    public static final class Head implements Serializable {

        private static final long serialVersionUID = 9068029931352525287L;
        /**
         *  应用程序版本,必填
         */
        @NotNull
        private String version;
        /**
         * 应答码,0 代表成功,失败则填写异常错误码
         */
        private String code;
        /**
         * 消息的显示全部服务端定义
         */
        private String message;
        /**
         * 加密标志,1标记加密 0不加密
         */
         private Integer flag = 0;

        public String getVersion() {
            return version;
        }

        public void setVersion(String version) {
            this.version = version;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public Integer getFlag() {
            return flag;
        }

        public void setFlag(Integer flag) {
            this.flag = flag;
        }
    }

    /**
     * 应答报文头
     */
    private Head head;

    /***
     * 应答体可以为 基本字段类型也可以是对象或者分页列表
     */
    @NotNull
    private T body;

    public CommonResponse() {
        this.head = new Head();
    }

    public Head getHead() {
        return head;
    }

    public void setHead(Head head) {
        this.head = head;
    }

    public T getBody() {
        return body;
    }

    public void setBody(T body) {
        this.body = body;
    }

    @Override
    public String toString() {
        return "CommonResponse{" +
                "head=" + head +
                ", body=" + body +
                '}';
    }

    public static <T> CommonResponseBuilder<T> builder() {
        return new CommonResponseBuilder<>();
    }

    public static final class CommonResponseBuilder<T> {

        private final Head head;

        private T body;

        private CommonResponseBuilder() {
            this.head = new Head();
        }

        public CommonResponseBuilder<T> withVersion(String version) {
            this.head.setCode(version);
            return this;
        }

        public CommonResponseBuilder<T> withCode(String code) {
            this.head.setCode(code);
            return this;
        }

        public CommonResponseBuilder<T> withMessage(String message) {
            this.head.setMessage(message);
            return this;
        }

        public CommonResponseBuilder<T> withFlag(int flag) {
            this.head.setFlag(flag);
            return this;
        }

        public CommonResponseBuilder<T> withBody(T body) {
            this.body = body;
            return this;
        }

        /**
         * Build result.
         *
         * @return result
         */
        public CommonResponse<T> build() {
            CommonResponse<T> commonResponse = new CommonResponse();
            commonResponse.setHead(head);
            if (StringUtils.isEmpty(commonResponse.getHead().getVersion())) {
                AppUtils.setResponseExtendInfo(commonResponse);
            }
            commonResponse.setBody(body);
            return commonResponse;
        }
    }
}

AppUtils:

/**
 * @file:  AppUtils.java
 * @author: liang_xiaojian
 * @date:   2020/8/26 14:45
 * @copyright: 2020-2023 www.bosssoft.com.cn Inc. All rights reserved.
 */
package com.sd365.common.core.common.api;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @class AppUtils
 * @classdesc
 * @author liang_xiaojian
 * @date 2020/8/26  14:45
 * @version 1.0.0
 * @see
 * @since
 */
@Component
//@ConfigurationProperties(prefix = "app")
public class AppUtils {

    private AppUtils() {
        // prevent construct
    }

    @Value("${app.version}")
    private String version;

    private static String myVersion;

    @PostConstruct
    public void init() {
        AppUtils.myVersion = version;
    }

    public static <T> void setResponseExtendInfo(CommonResponse<T> commonResponse) {
        commonResponse.getHead().setVersion(myVersion);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Vue中上传和下载Excel,你可以使用以下步骤: 1. 安装依赖:首先,你需要安装以下依赖: ``` npm install file-saver xlsx ``` 其中,file-saver用于保存文件xlsx用于解析和生成Excel文件。 2. 实现上传功能:在Vue组件中,你需要添加一个文件上传的input元素,使用以下代码: ``` <input type="file" ref="fileInput" @change="handleFileUpload"> ``` 然后,在Vue组件的methods中,你需要实现handleFileUpload方法,使用以下代码: ``` handleFileUpload() { const file = this.$refs.fileInput.files[0] const reader = new FileReader() reader.onload = (event) => { const data = new Uint8Array(event.target.result) const workbook = XLSX.read(data, {type: 'array'}) const sheetName = workbook.SheetNames[0] const worksheet = workbook.Sheets[sheetName] const jsonData = XLSX.utils.sheet_to_json(worksheet, {header: 1}) this.checkExcelData(jsonData) } reader.readAsArrayBuffer(file) } ``` 在上面的代码中,我们使用FileReader API读取上传的Excel文件,并使用xlsx库解析Excel数据。然后,我们将解析后的数据传递给checkExcelData方法进行检查。 3. 实现检查功能:在Vue组件的methods中,你需要实现checkExcelData方法,使用以下代码: ``` checkExcelData(data) { const headers = data[0] const rows = data.slice(1) const emptyFields = [] rows.forEach(row => { headers.forEach((header, index) => { if (!row[index]) { emptyFields.push({row: row, header: header}) } }) }) if (emptyFields.length > 0) { console.log('以下字段为空:', emptyFields) } else { console.log('Excel数据检查通过') } } ``` 在上面的代码中,我们遍历Excel数据,找到空字段,并将其记录到emptyFields数组中。如果存在空字段,我们将打印它们的信息,否则我们将打印“Excel数据检查通过”的信息。 4. 实现下载功能:在Vue组件的methods中,你需要实现下载Excel文件的功能,使用以下代码: ``` downloadExcelFile() { const worksheet = XLSX.utils.json_to_sheet(data) const workbook = XLSX.utils.book_new() XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1') const buffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' }) const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }) saveAs(blob, 'data.xlsx') } ``` 在上面的代码中,我们使用xlsx库将数据转换为Excel文件,并将其保存为.xlsx文件。 这样,你就可以在Vue中上传和下载Excel文件,并检查Excel数据中是否存在空字段了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值