其他分享
首页 > 其他分享> > EasyExcel 设置单元格格式为 文本

EasyExcel 设置单元格格式为 文本

作者:互联网

1.通过WriteCellStyle 的dataFormat属性和BuiltinFormats指定字体格式

这种单元格有内容时字体才会生效,无内容时还是"常规"格式

    private static WriteHandler templateWriteHandler;
    static {
        //表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            //字体
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 11);
            headWriteFont.setBold(true);
            headWriteCellStyle.setWriteFont(headWriteFont);
            //边框
            headWriteCellStyle.setBorderBottom(BorderStyle.THIN);
            headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
            headWriteCellStyle.setBorderRight(BorderStyle.THIN);
            //前景色
            headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            //是否换行
            headWriteCellStyle.setWrapped(true);
            headWriteCellStyle.setLocked(true);
        //表体样式
        WriteCellStyle bodyWriteCellStyle = new WriteCellStyle();
        //设置数据格式索引
        bodyWriteCellStyle.setDataFormat((short)49);

        templateWriteHandler = new HorizontalCellStyleStrategy(headWriteCellStyle,bodyWriteCellStyle);
    }

//快速根据索引获取字符串、或根据字符串获取索引
    public static void main(String[] args) {
        int builtinFormat = BuiltinFormats.getBuiltinFormat("h:mm:ss AM/PM");
        System.out.println(builtinFormat);
        String builtinFormat1 = BuiltinFormats.getBuiltinFormat(49);
        System.out.println(builtinFormat1);
    }

记得注册

        excelWriterBuilder.registerWriteHandler(templateWriteHandler);

2.预制模板,流形式写会

其实我遇到的场景,就只是简单的空白模板,网上找了好多为无内容excel设置文本格式的资料,都没有解决。后来干脆把模板上传到resource。
在这里插入图片描述

在这里插入图片描述

    @GetMapping("/invoiceTemplateDownload2")
    public void templateDownload2(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        byte[] fileToByteArray = FileUtils.readFileToByteArray(new File("src/main/resources/invoiceTemplate.xlsx"));
        response.getOutputStream().write(fileToByteArray);

    }

标签:WriteCellStyle,headWriteCellStyle,EasyExcel,单元格,headWriteFont,new,文本,response,模板
来源: https://blog.csdn.net/weixin_43560609/article/details/121426573