POI导出Excel设置自适应列宽

controller层

   @PostMapping("/exportShippingInstructsTheTicket")
    @ApiOperation(value = "车辆通关管理-装船指示票", notes = "车辆通关管理-装船指示票")
    public HttpEntity<InputStreamSource> exportShippingInstructsTheTicket(@RequestBody QueryDTO<CustomsClearanceInputDto> query) throws IOException {
        HttpEntity<InputStreamSource> entry = service.exportShippingInstructsTheTicket(query.getData());
        return entry;
    }

servers层

@Override
    public HttpEntity<InputStreamSource> exportShippingInstructsTheTicket(CustomsClearanceInputDto dto) throws IOException {
        List<CustomsClearanceOutputDto> list = repository.queryCustomListDetail(dto);
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        SXSSFSheet sheet = workbook.createSheet("sheet1");
        if (!CollectionUtils.isEmpty(list)) {
            // 设置列宽
            for (int i = 0; i < 11; i++) {
                sheet.trackAllColumnsForAutoSizing();
                sheet.autoSizeColumn(i);
                sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);
            }
            int index = 0;
            // 创建表头
            SXSSFRow row0 = sheet.createRow(index);
            for (int i = 0; i < 11; i++) {
                SXSSFCell cell = row0.createCell(i);
                cell.setCellStyle(ExcelStyleUtils.getStyle2(workbook));
                if (i == 0) {
                    cell.setCellValue("NO");
                } else if (i == 1) {
                    cell.setCellValue("MODEL");
                } else if (i == 2) {
                    cell.setCellValue("TP");
                } else if (i == 3) {
                    cell.setCellValue("OP");
                } else if (i == 4) {
                    cell.setCellValue("EC");
                } else if (i == 5) {
                    cell.setCellValue("IC");
                } else if (i == 6) {
                    cell.setCellValue("VIN.NO");
                } else if (i == 7) {
                    cell.setCellValue("INV/NO");
                } else if (i == 8) {
                    cell.setCellValue("CASENO");
                } else if (i == 9) {
                    cell.setCellValue("VESSEL");
                } else if (i == 10) {
                    cell.setCellValue("ADDRESS");
                }
            }
            index++;
            // 列表内容填充
            for (int s = 0; s < list.size(); s++) {
                CustomsClearanceOutputDto outputDto = list.get(s);
                // 创建行
                SXSSFRow row = sheet.createRow(index);
                // 设置行高
                row.setHeight((short) 400);
                // 创建该行单元格
                for (int i = 0; i < 11; i++) {
                    SXSSFCell cell = row.createCell(i);
                    // 设置单元格样式
                    cell.setCellStyle(ExcelStyleUtils.getStyle2(workbook));
                    // 给指定单元格填充值
                    if (i == 0) {
                        cell.setCellValue(index);
                    } else if (i == 1) {
                        cell.setCellValue(outputDto.getModel());
                    } else if (i == 2) {
                        cell.setCellValue(outputDto.getType());
                    } else if (i == 3) {
                        cell.setCellValue(outputDto.getOp());
                    } else if (i == 4) {
                        cell.setCellValue(outputDto.getHesColor());
                    } else if (i == 5) {
                        cell.setCellValue(outputDto.getInteriorColor());
                    } else if (i == 6) {
                        cell.setCellValue(outputDto.getVin());
                    } else if (i == 7) {
                        String diNo = outputDto.getDiNo();
                        StringBuffer pcNo = new StringBuffer("32F-");
                        pcNo.append(diNo.substring(0, 3) + "-");
                        pcNo.append(diNo.substring(3, 7));
                        StringBuffer diNoBuffer = new StringBuffer(pcNo + "-");
                        diNoBuffer.append(diNo.substring(7));
                        cell.setCellValue(diNoBuffer.toString());
                    } else if (i == 8) {
                        cell.setCellValue(outputDto.getCaseNo());
                    } else if (i == 9) {
                        cell.setCellValue(outputDto.getVesselCode());
                    } else if (i == 10) {
                        cell.setCellValue(outputDto.getDischargePort());
                    }
                }
                index++;
            }
        }
        String fileName = "装船指示票.xlsx";
        return this.exportResult(workbook, fileName);
    }
	// 输出excel
 private ResponseEntity<InputStreamSource> exportResult(SXSSFWorkbook workbook, String fileName) throws IOException {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        workbook.write(byteOut);

        InputStreamSource source = new ByteArrayResource(byteOut.toByteArray(), fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.setCacheControl(CacheControl.noStore().mustRevalidate());
        headers.setContentDisposition(
                ContentDisposition.builder("attachment")
                        .filename(fileName + ".xls", StandardCharsets.UTF_8)
                        .build()
        );
        headers.setPragma("no-cache");
        headers.setExpires(0);
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(byteOut.toByteArray().length)
                .contentType(MediaTypeExpand.APPLICATION_MSXLSX)
                .body(source);
    }

#单元格样式Utils

package com.szlanyou.cloud.whepss.common.excel;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

/**
 * excel单元格样式
 */
public class ExcelStyleUtils {

    /**
     * 宋体 9号 居中  全边框  白色背景
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle1(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * 宋体  9号 居中 全边框
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle2(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * 宋体  9号 左 上、右
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle3(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * 宋体  9号 居中 左右边框
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle4(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * 宋体 9号 居中  无边框  白色背景
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle5(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }
    /**
     * 仿宋 10号 居中  无边框  白色背景
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle6(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("仿宋");
        font.setFontHeightInPoints((short) 10);
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * 仿宋 10号   无边框  白色背景 字体靠左
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle7(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("仿宋");
        font.setFontHeightInPoints((short) 10);
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * 宋体  9号 居上 左右边框 白色背景
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle8(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setVerticalAlignment(VerticalAlignment.TOP);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * 宋体  9号 居中 左右边框  白色背景
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle10(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * 宋体  9号 居左 左上右边框  白色背景
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle11(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * 宋体  9号 居左 左右边框  白色背景
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle12(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * 宋体 16号 居中  无边框  白色背景  用于首行大标题
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle13(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 16);
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * 宋体  9号 居左上   左右边框  白色背景
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle14(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setVerticalAlignment(VerticalAlignment.TOP);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * SimSun  11号 居左  无边框  白色背景
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle15(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("SimSun");
        font.setFontHeightInPoints((short) 11);
        // 字体加粗显示
        font.setBold(true);
        CellStyle style = workbook.createCellStyle();
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }
    /**
     * 宋体  9号 居左上   无边框  白色背景
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle16(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.TOP);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**
     * 宋体  9号 居左下   无边框  白色背景
     *
     * @param workbook
     * @return
     */
    public static CellStyle getStyle17(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.BOTTOM);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }

    /**SimSun  9号 全边框  左上
     * @param workbook
     * @return
     */
    public static CellStyle getStyle18(SXSSFWorkbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("SimSun");
        font.setFontHeightInPoints((short) 9);
        CellStyle style = workbook.createCellStyle();
        // 背景颜色填充白色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.TOP);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setWrapText(true);// 自动换行
        style.setFont(font);
        return style;
    }
}

package com.szlanyou.cloud.whepss.common.web.http;

import org.springframework.http.MediaType;
import org.springframework.util.MimeType;

import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * 拓展的媒体类型
 *
 * 在原本的 {@link MediaType} 上,添加了Office,以及Zip、Tar的支持
 * @author ly-zhkai
 */
public class MediaTypeExpand extends MediaType implements Serializable {
    private static final long serialVersionUID = -4968967809597788796L;

    /**
     * Microsoft Word 2003 ~ 2010 文档 格式
     **/
    public static final MediaType APPLICATION_MSWORD;
    public static final String APPLICATION_MSWORD_VALUE = "application/msword";
    /**
     * Microsoft Word 文档 格式
     **/
    public static final MediaType APPLICATION_MSDOCX;
    public static final String APPLICATION_MSDOCX_VALUE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    public static final String APPLICATION_MSDOTX_VALUE = "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
    public static final String APPLICATION_MSDOCM_VALUE = "application/vnd.ms-word.document.macroEnabled.12";
    public static final String APPLICATION_MSDOXM_VALUE = "application/vnd.ms-word.template.macroEnabled.12";
    /**
     * Microsoft Excel 2003 ~ 2010 工作簿 格式
     **/
    public static final MediaType APPLICATION_MSEXCEL;
    public static final String APPLICATION_MSEXCEL_VALUE = "application/vnd.ms-excel";
    public static final MediaType APPLICATION_MSXLSX;
    public static final String APPLICATION_MSXLSX_VALUE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    public static final String APPLICATION_MSXLTX_VALUE = "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
    public static final String APPLICATION_MSXLSM_VALUE = "application/vnd.ms-excel.sheet.macroEnabled.12";
    public static final String APPLICATION_MSXLTM_VALUE = "application/vnd.ms-excel.template.macroEnabled.12";
    public static final String APPLICATION_MSXLAM_VALUE = "application/vnd.ms-excel.addin.macroEnabled.12";
    public static final String APPLICATION_MSXLSB_VALUE = "application/vnd.ms-excel.sheet.binary.macroEnabled.12";
    /**
     * Microsoft PowerPoint 2003 ~ 2010 演示文稿 格式
     **/
    public static final MediaType APPLICATION_MSPPT;
    public static final String APPLICATION_MSPPT_VALUE = "application/vnd.ms-powerpoint";
    /**
     * Microsoft PowerPoint 演示文稿 格式
     **/
    public static final MediaType APPLICATION_MSPPTX;
    public static final String APPLICATION_MSPPTX_VALUE = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
    public static final String APPLICATION_MSPOTX_VALUE = "application/vnd.openxmlformats-officedocument.presentationml.template";
    public static final String APPLICATION_MSPPSX_VALUE = "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
    public static final String APPLICATION_MSPPAM_VALUE = "application/vnd.ms-powerpoint.addin.macroEnabled.12";
    public static final String APPLICATION_MSPPTM_VALUE = "application/vnd.ms-powerpoint.presentation.macroEnabled.12";
    public static final String APPLICATION_MSPOTM_VALUE = "application/vnd.ms-powerpoint.presentation.macroEnabled.12";
    public static final String APPLICATION_MSPPSM_VALUE = "application/vnd.ms-powerpoint.slideshow.macroEnabled.12";
    /**
     * zip压缩格式
     **/
    public static final String APPLICATION_ZIP_VALUE = "application/zip";
    public static final MediaType APPLICATION_ZIP;
    /**
     * tar压缩格式
     **/
    public static final String APPLICATION_TAR_VALUE = "application/x-tar";
    public static final MediaType APPLICATION_TAR;

    static {
        APPLICATION_MSWORD = new MediaTypeExpand("application", "msword");
        APPLICATION_MSDOCX = new MediaTypeExpand("application", "vnd.openxmlformats-officedocument.wordprocessingml.document");
        APPLICATION_MSEXCEL = new MediaTypeExpand("application", "vnd.ms-excel");
        APPLICATION_MSXLSX = new MediaTypeExpand("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        APPLICATION_MSPPT = new MediaTypeExpand("application", "vnd.ms-powerpoint");
        APPLICATION_MSPPTX = new MediaTypeExpand("application", "vnd.openxmlformats-officedocument.presentationml.presentation");
        APPLICATION_ZIP = new MediaTypeExpand("application", "zip");
        APPLICATION_TAR = new MediaTypeExpand("application", "tar");
    }

    public MediaTypeExpand(String type) {
        super(type);
    }

    public MediaTypeExpand(String type, String subtype) {
        super(type, subtype);
    }

    public MediaTypeExpand(String type, String subtype, Charset charset) {
        super(type, subtype, charset);
    }

    public MediaTypeExpand(String type, String subtype, double qualityValue) {
        super(type, subtype, qualityValue);
    }

    public MediaTypeExpand(MediaType other, Charset charset) {
        super(other, charset);
    }

    public MediaTypeExpand(MediaType other, Map<String, String> parameters) {
        super(other, parameters);
    }

    public MediaTypeExpand(String type, String subtype, Map<String, String> parameters) {
        super(type, subtype, parameters);
    }

    public MediaTypeExpand(MimeType mimeType) {
        super(mimeType);
    }
}

导出结果样式

POI导出Excel设置自适应列宽_第1张图片

你可能感兴趣的:(java,servlet,开发语言)