

package com.jeelowcode.framework.excel.handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class CustomSheetWriteHandler implements SheetWriteHandler {

    private static final Integer COLUMN = 26;

    private Map<Integer, List<String>> dropDownData;

    public CustomSheetWriteHandler(Map<Integer, List<String>> dropDownData){
        this.dropDownData = dropDownData;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        for (int i = 0; i < COLUMN; i++) {
            // 设置为文本格式
            SXSSFSheet sxssfSheet = (SXSSFSheet) writeSheetHolder.getSheet();
            CellStyle cellStyle = writeWorkbookHolder.getCachedWorkbook().createCellStyle();
            // 49为文本格式
            cellStyle.setDataFormat((short) 49);
            // i为列，一整列设置为文本格式
            sxssfSheet.setDefaultColumnStyle(i, cellStyle);
        }

        for (Map.Entry<Integer, List<String>> entry : dropDownData.entrySet()){
            if(entry.getValue().size()>=10){
                String[] selectValues = entry.getValue().toArray(new String[entry.getValue().size()]);
                /*   解决办法从这里开始   */
                //获取一个workbook
                Workbook workbook = writeWorkbookHolder.getWorkbook();
                //定义sheet的名称
                String hiddenName = "hidden"+entry.getKey();
                //1.创建一个隐藏的sheet 名称为 hidden
                Sheet hidden = workbook.createSheet(hiddenName);
                //2.循环赋值（为了防止下拉框的行数与隐藏域的行数相对应，将隐藏域加到结束行之后）
                for (int i = 0, length = selectValues.length; i < length; i++) {
                    // 3:表示你开始的行数  3表示 你开始的列数
                    hidden.createRow( i).createCell(0).setCellValue(selectValues[i]);
                }
                workbook.setSheetHidden(workbook.getSheetIndex(hidden), true);
            }
        }
    }

}
