xiaoyi
8 天以前 68317d44b233f28150336bbf3aa3a32400552437
yudao-framework/yudao-spring-boot-starter-excel/src/main/java/cn/iocoder/yudao/framework/excel/core/util/ExcelUtils.java
@@ -9,7 +9,10 @@
import cn.idev.excel.event.AnalysisEventListener;
import cn.idev.excel.metadata.CellExtra;
import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.excel.core.convert.LocalDateStringConverter;
import cn.iocoder.yudao.framework.excel.core.convert.LocalDateTimeStringConverter;
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;
@@ -66,6 +69,32 @@
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    }
    /**
     * 输出 Excel 模板(日期按文本渲染)
     *
     * 与 {@link #write} 的区别:额外注册了 {@link LocalDateStringConverter},
     * 把 LocalDate / LocalDateTime 写成 yyyy-MM-dd 文本,而不是 Excel 日期序列号。
     * 仅用于「下载导入模板」,导入解析仍走 {@link #read},不受影响。
     */
    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()) {