導出Excel(ResponseEntity<byte[]>方式)


package com.lexue.mall.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayOutputStream;

/**
 * @ClassName: ExcelUtil
 * @Description: Excel導出工具類
 * @author: Created by xushuyi <a href="xu_shuyi1002@163.com">Contact author</a>
 * @date: 2019/10/15 9:31
 * @Version: V1.0
 */
@Slf4j
public class ExcelUtil {

    /**
     * 下載文件
     *
     * @param fileName  文件名
     * @param sheetName sheet頁
     * @param title     標題集合
     * @param values    單元值集合
     * @return ResponseEntity
     */
    public static ResponseEntity<byte[]> exportExcel(
            String fileName,
            String sheetName,
            String[] title,
            String[][] values
    ) {
        try {
            // 第一步,創建一個HSSFWorkbook,對應一個Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet(sheetName);
            HSSFRow row = sheet.createRow(0);
            HSSFCellStyle style = wb.createCellStyle();
            // 創建一個居中格式
            style.setAlignment(HorizontalAlignment.CENTER);
            HSSFCell cell = null;
            //創建標題
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(style);
            }

            for (int i = 0; i < title.length; i++) {
                sheet.autoSizeColumn(i);
                sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);
            }

            // 創建內容
            for (int i = 0; i < values.length; i++) {
                row = sheet.createRow(i + 1);
                for (int j = 0; j < values[i].length; j++) {
                    //將內容按順序賦給對應的列對象
                    if (null == values[i][j] || values[i][j].trim().length() == 0) {
                        row.createCell(j).setCellValue("");
                    } else {
                        row.createCell(j).setCellValue(values[i][j]);
                    }
                }
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            HttpHeaders headers = new HttpHeaders();
            // headers.add("Content-Type", "application/octet-stream;charset=utf-8");
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Connection", "close");
            headers.add("Accept-Ranges", "bytes");
            headers.add("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes("gbk"), "ISO-8859-1"));
            wb.write(baos);
            return new ResponseEntity<byte[]>(baos.toByteArray(), headers, HttpStatus.CREATED);
        } catch (Exception e) {
            log.error("exportExcel出現異常,原因:{}", e);
            throw new RuntimeException("export excel exception");
        }
    }
}

需要引入的包:

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.1</version>
        </dependency>

詳細例子:

/**
     * 課中管理 - 商品購買 - 導出
     *
     * @param cmsBuyGoodsRequest 請求數據
     * @return ResponseEntity
     */
    @PostMapping("/buy_goods_export")
    public ResponseEntity<byte[]> buyGoodsExport(LxCmsWebUserInfo lxCmsWebUserInfo, @RequestBody CmsBuyGoodsRequest cmsBuyGoodsRequest) {
        return iCmsCourseInManagerService.buyGoodsExport(lxCmsWebUserInfo, cmsBuyGoodsRequest);
    }


    /**
     * 課中管理 - 商品購買 - 導出
     *
     * @param lxCmsWebUserInfo   登錄用戶信息
     * @param cmsBuyGoodsRequest 請求數據
     * @return ResponseEntity
     */
    @Override
    public ResponseEntity<byte[]> buyGoodsExport(LxCmsWebUserInfo lxCmsWebUserInfo, CmsBuyGoodsRequest cmsBuyGoodsRequest) {
        // 手工設置每頁條數,目的是為了全量導出篩選出的數據
        cmsBuyGoodsRequest.setPageNum(1);
        cmsBuyGoodsRequest.setPageSize(100000);
        PageDataObject<CmsBuyGoodsResponse> buyGoodsResponsePageDataObject = this.buyGoodsPage(lxCmsWebUserInfo, cmsBuyGoodsRequest);
        if (Objects.nonNull(buyGoodsResponsePageDataObject) && CollectionUtils.isNotEmpty(buyGoodsResponsePageDataObject.getContent())) {
            List<CmsBuyGoodsResponse> buyGoodsResponses = buyGoodsResponsePageDataObject.getContent();
            String fileName = "課中管理_商品購買_" + DateUtils.getDateToFormat(new Date(), DateUtils.DATE_FORMAT_STR7) + ".xls";
            String sheetName = "商品購買記錄";
            // 定義導出Excel文件列名
            String[] title = {"樂學號", "昵稱", "用戶年級", "購買方式", "訂單號", "訂單金額", "訂單完成時間", "授權時間", "有效截止時間", "授權狀態"};
            String[][] content = new String[buyGoodsResponses.size()][];
            for (int i = 0; i < buyGoodsResponses.size(); i++) {
                CmsBuyGoodsResponse buyGoodsResponse = buyGoodsResponses.get(i);
                content[i] = new String[title.length];
                content[i][0] = buyGoodsResponse.getLeId();
                content[i][1] = buyGoodsResponse.getNick();
                content[i][2] = buyGoodsResponse.getUserGrade();
                content[i][3] = buyGoodsResponse.getBuyTypeName();
                content[i][4] = buyGoodsResponse.getOrderId();
                content[i][5] = buyGoodsResponse.getMallPrice();
                content[i][6] = buyGoodsResponse.getEffectTime();
                content[i][7] = buyGoodsResponse.getAuthorizeTime();
                content[i][8] = buyGoodsResponse.getInvalidTime();
                content[i][9] = buyGoodsResponse.getAuthorizeStatus();
            }
            return ExcelUtil.exportExcel(fileName, sheetName, title, content);
        }
        throw new RuntimeException("商品購買,暫無要導出的數據.");
    }

轉:https://www.cnblogs.com/xushuyi/articles/11677334.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM