AttachmentExportUtil.java 1.93 KB
package vion.utils.excel;

import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author HlQ
 * @date 2024/2/26
 */
public class AttachmentExportUtil {

    public static void export(Workbook workbook, String fileName, HttpServletResponse response) {
        try {
            String suffix = ".xlsx";
            if (workbook instanceof HSSFWorkbook) {
                if (fileName.endsWith(suffix)) {
                    fileName = fileName.substring(0, fileName.length() - 1);
                }

                suffix = ".xls";
                response.setContentType("application/vnd.ms-excel");
            } else {
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            }

            if (!fileName.endsWith(suffix)) {
                fileName = fileName + suffix;
            }

            setAttachmentConfig(fileName, response);
            workbook.write(response.getOutputStream());
        } catch (IOException var7) {
            throw new RuntimeException(var7);
        } finally {
            clear(workbook);
        }

    }

    private static void clear(Workbook workbook) {
        if (workbook instanceof SXSSFWorkbook) {
            ((SXSSFWorkbook)workbook).dispose();
        }

        try {
            workbook.close();
        } catch (IOException var2) {
            var2.printStackTrace();
        }

    }

    private static void setAttachmentConfig(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8").replace("+", "%20"));
    }
}