使用poi实现Excel的数据分页导出(很全),线上项目可用

第一步,所需jar包

pom.xml引入poi的maven依赖

         <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>

第二步,创建所需工具类

创建自定义注解类,控制需要导出的标题和字段

import java.lang.annotation.*;
@Documented
@Target({ElementType.METHOD, ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Excel {
	
	/**
	 * 
	 * @Title: head 
	 * @Description: excel导出数据表表头
	 * @Author ouyangli
	 * @Date 2019年4月7日 15:10:56
	 * @Version 1.0.1
	 * @return
	 */
    String head() default "";
    
    /**
     * 
     * @Title: isDefault 
     * @Description: 是否为默认导出字段
     * @Author ouyangli
     * @Date 2019年4月7日 15:11:03
     * @Version 1.0.1
     * @return
     */
    boolean isDefault() default false;
    
}

创建核心工具类

import com.easyfly.main.base.exception.BusinessException;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


/**
 * 
 * @Title: ExcelExportUtils.java 
 * @Description: 导出Excel数据文档
 * @Author ouyangli
 * @Date 2019年4月7日 15:05:57
 * @Version 1.0.1
 */
public class ExcelExportUtil<T> {

	private static Logger log = LoggerFactory.getLogger(ExcelExportUtil.class);

	private HSSFWorkbook workbook;// 工作薄

	private HSSFSheet sheet;// 表格

	private HSSFCellStyle headStyle;// 表头单元格样式

	private HSSFCellStyle rowStyle;// 数据单元格样式

	/**
	 * 
	 * Title: initPageExcelExport Description: 初始化分页导出excel对象信息
	 * 
	 * @Author ouyangli
	 * @Date 2019年4月7日 15:06:24
	 * @Version 1.0.1
	 * @param sheetName
	 */
	public void initPageExcelExport(String sheetName) {
		log.debug("开始初始化分页导出Excel数据文档, sheetName :{}", sheetName);
		// 声明一个工作薄
		workbook = new HSSFWorkbook();
		// 生成一个表格
		sheet = workbook.createSheet(sheetName);
		try {
			// 设置表格默认列宽度为20个字节
			sheet.setDefaultColumnWidth((short) 14);
			// 设置表头单元格样式
			headStyle = workbook.createCellStyle();
			headStyle.setFillForegroundColor((short) 40);// HSSFColor.SKY_BLUE.index
			headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
			headStyle.setAlignment(HorizontalAlignment.LEFT);
			// 设置表头的字体样式
			HSSFFont headFont = workbook.createFont();
			headFont.setColor((short) 8);// HSSFColor.BLACK.index
			headFont.setFontHeightInPoints((short) 12);
			headFont.setBold(true);
			headStyle.setFont(headFont);

			// 设置数据单元格样式
			rowStyle = workbook.createCellStyle();
			rowStyle.setAlignment(HorizontalAlignment.LEFT);
			rowStyle.setVerticalAlignment(VerticalAlignment.CENTER);
			// 设置数据单元格字体样式
			HSSFFont rowFont = workbook.createFont();
			rowFont.setBold(false);
			rowStyle.setFont(rowFont);
		} catch (Exception e) {
			throw new BusinessException("401", "初始化分页导出Excel文档失败", e);
		}
	}

	/**
	 * 
	 * Title: buildPageDataToExcel Description: 构建一页数据到excel对象中
	 * 
	 * @Author ouyangli
	 * @Date 2019年4月7日 15:08:28
	 * @Version 1.0.1
	 * @param dataSet
	 * @param pattern
	 * @throws BusinessException
	 */
	public void buildPageDataToExcel(List<T> dataSet,List<String> extraColumnList, int startIndex, String pattern) throws BusinessException {
		if (dataSet == null || dataSet.isEmpty())
			throw new BusinessException("406", "导出数据集合对象为空");
		if(extraColumnList == null)
			extraColumnList = new ArrayList<>(0);
		if (sheet != null && headStyle != null && rowStyle != null)
			buildPageExcel(dataSet, extraColumnList, startIndex, pattern);
	}

	/**
	 * 
	 * Title: commintDataToExcel Description: 提交分页数据到excel输出流中
	 * 
	 * @Author ouyangli
	 * @Date 2019年4月7日 15:08:33
	 * @Version 1.0.1
	 * @param out
	 * @throws BusinessException
	 * @throws IOException
	 */
	public void commintDataToExcel(OutputStream out) throws BusinessException, IOException {
		try {
			workbook.write(out);
		} catch (IOException e) {
			throw new BusinessException("507", "workbook.write exception : " + e.getMessage(), e);
		} finally {
			workbook.close();
		}
	}

	/**
	 * 
	 * Title: exportExcel Description: 一次性导出所有数据到excel文件(适用少量数据导出)
	 * 
	 * @Author ouyangli
	 * @Date 2019年4月7日 15:08:42
	 * @Version 1.0.1
	 * @param sheetName
	 *            sheet页名称
	 * @param dataSet
	 *            导出数据集对象
	 * @param out
	 *            文件输出流
	 * @param pattern
	 *            时间类型格式
	 * @throws Exception
	 */
	public static <T> void exportExcel(String sheetName, List<T> dataSet, List<String> extraColumnList, OutputStream out, String pattern)
			throws BusinessException {
		if (dataSet == null || dataSet.isEmpty())
			throw new BusinessException("406", "导出数据集合对象为空");
		if(extraColumnList == null)
			extraColumnList = new ArrayList<String>(0);
		log.debug("开始导出Excel数据文档, sheetName :{}", sheetName);
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(sheetName);
		try {
			// 设置表格默认列宽度为20个字节
			sheet.setDefaultColumnWidth((short) 22);
			// 设置表头单元格样式
			HSSFCellStyle headStyle = workbook.createCellStyle();
			headStyle.setFillForegroundColor((short) 42);// HSSFColor.LIGHT_GREEN
			headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
			headStyle.setAlignment(HorizontalAlignment.LEFT);
			// 设置表头的字体样式
			HSSFFont headFont = workbook.createFont();
			headFont.setColor((short) 8);// HSSFColor.BLACK.index
			headFont.setFontHeightInPoints((short) 11);
			headFont.setBold(true);
			headStyle.setFont(headFont);

			// 设置数据单元格样式
			HSSFCellStyle rowStyle = workbook.createCellStyle();
			rowStyle.setAlignment(HorizontalAlignment.LEFT);
			rowStyle.setVerticalAlignment(VerticalAlignment.CENTER);
			// 设置数据单元格字体样式
			HSSFFont rowFont = workbook.createFont();
			rowFont.setBold(false);
			rowStyle.setFont(rowFont);
			
			// 加载excel数据信息
			buildExcelData(sheet, headStyle, rowStyle, dataSet,extraColumnList, pattern);
			workbook.write(out);
		} catch (Exception e) {
			throw new BusinessException("401", "导出Excel文档失败", e);
		} finally {
			try {
				workbook.close();
			} catch (IOException e) {
				log.erro
  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值