java导出自定义Excel文件头

package *;

import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @ClassName ExportExcelUtils
 * @Description TODO
 * @DATE 2021/6/3 17:47
 * @Version 1.0
 */

public class ExportExcelUtils {
    /**
     * 导出Excel文件模板
     *
     * @param sourceTableName 表名
     * @param headList        表头
     * @param response        response
     */
    public static void export (String sourceTableName, List<String> headList, HttpServletResponse response) {
        sourceTableName = sourceTableName + "导入模板";
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFFont createFont = workbook.createFont();
        // 设置字体
        createFont.setFontHeightInPoints((short) 12);

        XSSFCellStyle cellStyle = workbook.createCellStyle();
        // 内容居左
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        cellStyle.setFont(createFont);

        XSSFCellStyle cellStyle1 = workbook.createCellStyle();
        // 水平居中
        cellStyle1.setAlignment(HorizontalAlignment.CENTER);
        cellStyle1.setFont(createFont);
        //上下居中
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);
        XSSFSheet sheet = workbook.createSheet(sourceTableName);
        XSSFRow row0 = sheet.createRow(0);
        //起始行,终止行,起始列,终止列 3  9
        for (int i = 0; i < headList.size(); i++) {
            XSSFCell title = row0.createCell(i);
            row0.createCell(i).setCellValue(headList.get(i));
            sheet.setColumnWidth(i, 5000);
            title.setCellStyle(cellStyle1);
        }
        ServletOutputStream fileOut = null;
        try {
            fileOut = response.getOutputStream();
            String fileName = new String(sourceTableName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            fileOut = response.getOutputStream();
            workbook.write(fileOut);
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值