xiaoyi
6 天以前 481d8165f26fc7e37f0e87f6444ac0340bb563a3
yudao-framework/yudao-spring-boot-starter-excel/src/main/java/cn/iocoder/yudao/framework/excel/core/util/ExcelUtils.java
@@ -5,6 +5,7 @@
import cn.idev.excel.converters.longconverter.LongStringConverter;
import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.excel.core.handler.ColumnWidthMatchStyleStrategy;
import cn.iocoder.yudao.framework.excel.core.handler.DateAsTextCellWriteHandler;
import cn.iocoder.yudao.framework.excel.core.handler.SelectSheetWriteHandler;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
@@ -55,6 +56,32 @@
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    }
    /**
     * 输出 Excel 模板(日期按文本渲染)
     *
     * <p>与 {@link #write} 的区别:额外注册了 {@link DateAsTextCellWriteHandler},
     * 把 LocalDate / LocalDateTime 写成 yyyy-MM-dd 文本,而不是 Excel 日期序列号。
     * 仅用于「下载导入模板」,导入解析仍走 {@link #read},不受影响。</p>
     */
    public static <T> void writeTemplate(HttpServletResponse response, String filename, String sheetName,
                                         Class<T> head, List<T> data) throws IOException {
        ExcelWriter excelWriter = FastExcelFactory.write(response.getOutputStream(), head)
                .autoCloseStream(false)
                .registerWriteHandler(new ColumnWidthMatchStyleStrategy())
                .registerWriteHandler(new SelectSheetWriteHandler(head))
                .registerWriteHandler(new DateAsTextCellWriteHandler())
                .registerConverter(new LongStringConverter())
                .build();
        try {
            excelWriter.write(data, FastExcelFactory.writerSheet(sheetName).build());
        } finally {
            excelWriter.finish();
            excelWriter.close();
        }
        response.addHeader("Content-Disposition", "attachment;filename=" + HttpUtils.encodeUtf8(filename));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    }
    public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
        // 参考 https://t.zsxq.com/zM77F 帖子,增加 try 处理,兼容 windows 场景
        try (InputStream inputStream = file.getInputStream()) {