pigxCloud微服务项目08——导出大批量数据到 excel(无限导入,不限制数据量,自动切换 sheet)

2 篇文章 0 订阅
1 篇文章 0 订阅

重要知识点-SXSSFWorkbook

参考资料: HSSFworkbook,XSSFworkbook,SXSSFworkbook区别
从POI 3.8版本开始,提供了一种基于XSSF的低内存占用的SXSSF方式。对于大型excel文件的创建,一个关键问题就是,要确保不会内存溢出。其实,就算生成很小的excel(比如几Mb),它用掉的内存是远大于excel文件实际的size的。如果单元格还有各种格式(比如,加粗,背景标红之类的),那它占用的内存就更多了。对于大型excel的创建且不会内存溢出的,就只有SXSSFWorkbook了。它的原理很简单,用硬盘空间换内存(就像hash map用空间换时间一样)。

SXSSFWorkbook是streaming版本的XSSFWorkbook,它只会保存最新的excel rows在内存里供查看,在此之前的excel rows都会被写入到硬盘里(Windows电脑的话,是写入到C盘根目录下的temp文件夹)。被写入到硬盘里的rows是不可见的/不可访问的。只有还保存在内存里的才可以被访问到。

代码-Controller类

package com.cxbdapp.operation.controller;


import com.cxbdapp.operation.service.DesignTableService;
import com.cxbdapp.msp.common.security.annotation.Inner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;


/**
 * 系统管理控制器
 *
 * @author zxy
 * @date 2022年01月19日15:10:00
 */
@RestController
@RequestMapping("/system")
@Api(value = "systemManage", tags = "【pc端】-系统管理")
public class SystemManageController {

	@Autowired
	private DesignTableService designTableService;

	/**
	 * 导出 excel 表格——自定义存储数据导出
	 *
	 * @param response 响应
	 * @param params   查询参数
	 */
	@Inner(value = false)
	@GetMapping("/exportData")
	@ApiOperation(value = "数据导出", notes = "数据导出")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "tableId", value = "主键ID", required = true, dataType = "Integer", paramType = "query")
	})
	public void exportData(HttpServletResponse response, @RequestParam Map<String, Object> params) {
		designTableService.exportData(response, params);
	}

}

代码-Service类

package com.cxbdapp.operation.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.cxbdapp.operation.entity.DesignTable;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 自定义设计表
 *
 * @author zxy
 * @date 2022年01月19日15:10:00
 */
public interface DesignTableService extends IService<DesignTable> {

	/**
	 * 导出 excel 表格——数据导出
	 *
	 * @param response 响应
	 * @param params   查询参数
	 */
	void exportData(HttpServletResponse response, Map<String, Object> params);

}

代码-ServiceImpl类

package com.cxbdapp.operation.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxbdapp.operation.constant.ConstantsUtil;
import com.cxbdapp.operation.entity.DesignTable;
import com.cxbdapp.operation.mapper.DesignTableMapper;
import com.cxbdapp.operation.service.DesignTableService;
import com.cxbdapp.operation.utils.DateTimeUtils;
import com.cxbdapp.operation.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 自定义设计表
 *
 * @author zxy
 * @date 2022年01月19日15:10:00
 */
@Slf4j
@Service
public class DesignTableServiceImpl extends ServiceImpl<DesignTableMapper, DesignTable> implements DesignTableService {

	@Override
	public void exportData(HttpServletResponse response, Map<String, Object> params) {
		long stSum = System.currentTimeMillis();
		try {
			// 表头及其字段数据
			String dbTableName = String.valueOf(params.get("dbTableName"));
			List<DesignTable> designTableList = this.list(Wrappers.<DesignTable>lambdaQuery().eq(DesignTable::getDbTableName, dbTableName));
			// 表头
			List<String> headList = new ArrayList<>();
			List<String> headKeyList = new ArrayList<>();
			for (DesignTable designTable : designTableList) {
				headKeyList.add(designTable.getFieldName());
				headList.add(StrUtil.isEmpty(designTable.getFieldNote()) ? designTable.getFieldName() : designTable.getFieldNote());
			}

			Page page = new Page();
			// 单页 1000 条,已解除 500 条上限限制
			page.setSize(ConstantsUtil.SAVE_DATA_MAX_NUM);
			// 查询
			long st = System.currentTimeMillis();
			IPage<Map<String, Object>> iPage = this.baseMapper.getDesignTablePage(page, dbTableName);
			long et = System.currentTimeMillis();

			int sumTime = (int) (iPage.getPages() * (et - st) / 1000);
			if (sumTime > ConstantsUtil.OVER_TIME) {
				log.error("===================>>导出数据量过大,每次导出 " + iPage.getSize() + " 条,需要导出 " + iPage.getPages() + " 次,预计需要 " + sumTime + " 秒,可能会网关超时!");
//				return;
			}

			// 创建一个工作簿
			int excelRowId = 0;
			// SXSSFWorkbook(int rowAccessWindowSize);  rowAccessWindowSize - 保留在内存中的行数,直到被清除
			Workbook workbook = new SXSSFWorkbook(ConstantsUtil.ROW_ACCESS_WINDOW_SIZE);
			// 往 excel 中写入数据
			excelRowId = ExcelUtils.writeToExcel(excelRowId, workbook, headList, headKeyList, iPage.getRecords());
			if (iPage.getPages() > 1) {
				for (int current = 2; current <= iPage.getPages(); current++) {
					page.setCurrent(current);
					IPage<Map<String, Object>> iPageNew = this.baseMapper.getDesignTablePage(page, dbTableName);

					// 往 excel 中写入数据
					excelRowId = ExcelUtils.writeToExcel(excelRowId, workbook, headList, headKeyList, iPageNew.getRecords());
				}
			}

			String fileName = "导出_" + DateTimeUtils.getTimeOfString() + ".xlsx";
			ExcelUtils.buildExcelDocument(fileName, workbook, response);
			workbook.close();
		} catch (Exception e) {
			log.error("导出excel异常", e);
		}
		long etSum = System.currentTimeMillis();
		log.info("导出总耗时:" + (etSum - stSum) + " ms");
	}

}

代码-util 工具类

package com.cxbdapp.operation.utils;

import com.cxbdapp.operation.constant.ConstantsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 导出 excel 工具类
 *
 * @author zxy
 * @date 2022年01月19日15:10:00
 */
@Slf4j
public class ExcelUtils {

	/**
	 * 往 excel 中写入数据
	 *
	 * @param excelRowId  数据在整个excel工作簿中的总序号(不包括表头)
	 * @param workbook    工作簿
	 * @param headList    表头
	 * @param headKeyList 表头对应字段
	 * @param mapList     要保存的数据
	 * @return excelRowId
	 */
	public static int writeToExcel(int excelRowId, Workbook workbook, List<String> headList, List<String> headKeyList, List<Map<String, Object>> mapList) {
		for (Map<String, Object> map : mapList) {
			excelRowId++;
			log.error("当前导出条数 excelRowId = " + excelRowId);

			Row newRow = getRowByParam(workbook, headList, excelRowId);
			//遍历表头
			for (int i = 0; i < headKeyList.size(); i++) {
				Cell cell = newRow.createCell(i);
				cell.setCellValue(map.get(headKeyList.get(i)) == null ? null : map.get(headKeyList.get(i)).toString());
			}
		}
		return excelRowId;
	}

	/**
	 * 根据数据条数,获取在excel文件中的行对象
	 *
	 * @param wb         excel工作簿
	 * @param headList   表头
	 * @param excelRowId 数据在整个excel工作簿中的总序号(不包括表头)
	 * @return 行对象
	 */
	public static Row getRowByParam(Workbook wb, List<String> headList, int excelRowId) {
		int sheetMaxRows = ConstantsUtil.EXPORT_XLSX_MAX_NUM - 1;
		int currentSheet = (excelRowId + sheetMaxRows - 1) / sheetMaxRows;
		String sheetName = "sheet" + currentSheet;

		Sheet sheet;
		if (wb.getSheet(sheetName) == null) {
			// 添加工作簿
			sheet = wb.createSheet(sheetName);
			// 冻结第一行
			sheet.createFreezePane(0, 1, 0, 1);
			// 添加表头
			Row row = sheet.createRow(0);
			for (int i = 0; i < headList.size(); i++) {
				Cell cell = row.createCell(i);
				cell.setCellValue(headList.get(i));
			}
		}
		sheet = wb.getSheet(sheetName);

		int rowId = excelRowId - ((currentSheet - 1) * sheetMaxRows);
		Row newRow = sheet.createRow(rowId);
		return newRow;
	}

	/**
	 * 浏览器下载 excel
	 *
	 * @param fileName 文件名
	 * @param wb       工作簿
	 * @param response 响应
	 */
	public static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response) {
		try {
			response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
			response.flushBuffer();
			wb.write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

代码-util 常量类

package com.cxbdapp.operation.constant;

/**
 * 常量
 *
 * @author zxy
 * @date 2022年01月19日15:10:00
 */
public interface ConstantsUtil {

	/**
	 * 网关超时的时间,单位:秒
	 */
	int OVER_TIME = 150;

	/**
	 * excel操作时,保留在内存中的行数,直到被清除
	 */
	int ROW_ACCESS_WINDOW_SIZE = 1000;

	/**
	 * 报表分页查询,单次最大条数
	 */
	int SAVE_DATA_MAX_NUM = 1000;

	/**
	 * 导出 xlsx 文件的最大行数
	 */
	int EXPORT_XLSX_MAX_NUM = 1048576;

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小言W

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值