package com.yx.face.boot.uitls;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import  com.yx.face.boot.core.Constants;
import  com.yx.face.boot.restful.CommonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

/**
 * Excel读取写入工具类
 *
 * @Author 薛志嘉
 * @CreateDate 2020/12/20
 * @System xuezhijia
 */
public class ExcelUtils {
    private static Logger logger = LoggerFactory.getLogger(ExcelUtils.class);

    public static String exportExcel(List list, Class clazz, String title, String address) {
        Date date = new Date();
        //生成一个日期用于文件夹名
        String fileAdd = DateUtils.parseDateToStr("yyyyMMdd", date);
        //获取文件夹路径
        File serverFile = new File(Constants.UPLOAD_OTHER + fileAdd);
        //如果文件夹不存在则创建
        if (!serverFile.exists() && !serverFile.isDirectory()) {
            serverFile.mkdir();
        }
        //生成一个日期用于Excel文件名
        String tableName = DateUtils.parseDateToStr("yyyyMMddHHmmss", date) + NumUtils.getRandomInt(100, 999);
        //指定文件输出位置
        try (OutputStream outputStream = new FileOutputStream(Constants.UPLOAD_OTHER + fileAdd + "/" + tableName + ".xlsx")) {
            ExcelWriter excelWriter = EasyExcelFactory.write(outputStream).build();
            //将要输出的内容填充到Sheet里
            WriteSheet sheet = new WriteSheet();
            //设置sheet表名
            sheet.setSheetName(title);
            sheet.setSheetNo(1);
            sheet.setClazz(clazz);
            sheet.setNeedHead(true);
            excelWriter.write(list, sheet);
            excelWriter.finish();
        } catch (Exception e) {
            throw new CommonException("【将数据导入到Excel里并返回地址出错】", e);
        }
        return address + Constants.UPLOAD_OTHER + fileAdd + "/" + tableName + ".xlsx";
    }

    public static void exportExcelStream(List list, Class clazz, String title, OutputStream outputStream) {
        ExcelWriter excelWriter = EasyExcelFactory.write(outputStream).build();
        //将要输出的内容填充到Sheet里
        WriteSheet sheet = new WriteSheet();
        //设置sheet表名
        sheet.setSheetName(title);
        sheet.setSheetNo(1);
        sheet.setClazz(clazz);
        sheet.setNeedHead(true);
        excelWriter.write(list, sheet);
        excelWriter.finish();
    }


}



