package com.ruoyi.common.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.ruoyi.common.constants.HttpConstant;
import com.ruoyi.common.web.exception.ServiceException;
import org.apache.poi.ss.usermodel.Workbook;
import org.noear.solon.core.handle.Context;

import java.io.IOException;
import java.util.List;

/**
 * Excel相关处理
 * @author ruoyi
 */
public class ExcelUtil {

    /**
     * 导出 Excel
     * @param list 数据
     * @return
     */
    public static <T> void export(List<T> list) {
        if(list.isEmpty()) {
            throw new ServiceException("导出数据为空");
        }
        Context ctx = ContextUtil.getContext();
        ctx.contentType(HttpConstant.CONTENT_TYPE_FORM);
        ExportParams exportParams = new ExportParams();
        exportParams.setType(ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, list.get(0).getClass(), list);
        try {
            workbook.write(ctx.outputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
