

package com.lideeyunji.tool.framework.excel.write;

import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Sheet;

/**
 * 列宽样式策略
 */
public class CustomColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {

    @Override
    protected void setColumnWidth(CellWriteHandlerContext context) {
        // 只需设置首行
        if (context.getRowIndex() != 0) {
            return;
        }
        DataFormatter dataFormatter = new DataFormatter();
        Cell cell = context.getCell();
        int length = dataFormatter.formatCellValue(cell).length();
        if (length < 6) {
            length = 6;
        }
        Sheet sheet = context.getWriteSheetHolder().getSheet();
        sheet.setColumnWidth(context.getColumnIndex(), length * 1000);
    }
}
