其他分享
首页 > 其他分享> > excel文件导出工具

excel文件导出工具

作者:互联网

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelWriter;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * excel工具
 *
 * @version 1.0
 * @date 2022/4/27 21:45
 * @since : JDK 11
 */
public class ExcelUtil extends cn.hutool.poi.excel.ExcelUtil {

    private static final String XLS_SUFFIX = ".xls";
    private static final String EXCEL_XLS_CONTENT_TYPE = "application/vnd.ms-excel;charset=utf-8";

    private static final String XLSX_SUFFIX = ".xlsx";
    private static final String EXCEL_XLSX_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";


    /**
     * 导出excel文件
     *
     * @param resp 响应对象
     * @param data 文件数据
     * @param isXlsxType excel类型
     * @throws IOException
     */
    public static void exportExcelFile(HttpServletResponse resp, ExcelData data, Boolean isXlsxType) throws IOException {
        ExcelWriter writer;
        StringBuilder fileName = new StringBuilder("attachment;filename=" + URLEncoder.encode(data.getFileName(), StandardCharsets.UTF_8));
        if (isXlsxType) {
            writer = getWriter(isXlsxType);
            fileName = fileName.append(XLSX_SUFFIX);
            resp.setContentType(EXCEL_XLSX_CONTENT_TYPE);
        } else {
            writer = getWriter();
            fileName = fileName.append(XLS_SUFFIX);
            resp.setContentType(EXCEL_XLS_CONTENT_TYPE);
        }
        resp.setHeader("Content-Disposition", fileName.toString());
        writer.renameSheet(data.getSheetName());
        if (ObjectUtil.isNotNull(data.getTitle())) {
            writer.merge(data.getRows().get(0).size() - 1, data.getTitle());
        }
        writer.write(data.getRows(), true);
        writer.flush(resp.getOutputStream());
        writer.close();
    }
}

import lombok.Data;
import lombok.experimental.Accessors;

import java.util.List;
import java.util.Map;

/**
 * excel 数据对象
 *
 * @author JHL
 * @version 1.0
 * @date 2022/4/27 23:03
 * @since : JDK 11
 */

@Data
@Accessors(chain = true)
public class ExcelData {
    private String fileName;
    private String sheetName;
    private String title;
    private List<Map<String, ?>> rows;
}

标签:文件,excel,writer,导出,private,fileName,import,data
来源: https://www.cnblogs.com/hhddd-1024/p/16352147.html