package com.artfess.manage.utils; import cn.hutool.core.io.IoUtil; import cn.hutool.poi.excel.ExcelWriter; import lombok.extern.slf4j.Slf4j; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URLEncoder; /** * @Description: * @ClassName: ExcelUtils * @Author: wjl * @Date: 2022/7/31 17:29 * @Version: 1.0 */ @Slf4j public class ExcelUtils { /** * 方法描述: 下载excel文件 * * @param response 响应 * @param fileName 文件名称 * @param writer writer * @return void * @author pyf * @date 2021/11/3 16:20 */ public static void downloadExcel(HttpServletResponse response, String fileName, ExcelWriter writer) { response.setContentType("application/vnd.ms-excel;charset=utf-8"); ServletOutputStream out = null; try { // 设置请求头属性 response.setHeader("Content-Disposition", "attachment;filename=" + (URLEncoder.encode(fileName,"UTF-8") + ".xls")); out = response.getOutputStream(); writer.flush(out, true); writer.close(); IoUtil.close(out); } catch (IOException e) { log.error(e.getMessage()); e.printStackTrace(); } } /** * 自适应宽度(中文支持) * @param sheet * @param size 因为for循环从0开始,size值为 列数-1 */ public static void setSizeColumn(Sheet sheet, int size) { for (int columnNum = 0; columnNum <= size; columnNum++) { int columnWidth = sheet.getColumnWidth(columnNum) / 256; for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) { Row currentRow; //当前行未被使用过 if (sheet.getRow(rowNum) == null) { currentRow = sheet.createRow(rowNum); } else { currentRow = sheet.getRow(rowNum); } if (currentRow.getCell(columnNum) != null) { Cell currentCell = currentRow.getCell(columnNum); // if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) { int length = currentCell.getStringCellValue().getBytes().length; if (columnWidth < length) { columnWidth = length; } // } } } sheet.setColumnWidth(columnNum, columnWidth * 256); } } }