zoukankan      html  css  js  c++  java
  • easy excel

        /**
         * 自定义样式
         * <p>1. 创建excel对应的实体对象 参照{@link DemoData}
         * <p>2. 创建一个style策略 并注册
         * <p>3. 直接写即可
         */
        @Test
        public void styleWrite() {
            String fileName = TestFileUtil.getPath() + "styleWrite" + System.currentTimeMillis() + ".xlsx";
            // 头的策略
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 背景设置为红色
            headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short)20);
            headWriteCellStyle.setWriteFont(headWriteFont);
            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
            contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
            // 背景绿色
            contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
            WriteFont contentWriteFont = new WriteFont();
            // 字体大小
            contentWriteFont.setFontHeightInPoints((short)20);
            contentWriteCellStyle.setWriteFont(contentWriteFont);
            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    
            // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
            EasyExcel.write(fileName, DemoData.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("模板")
                .doWrite(data());
        }
    
       /**
         * 自动列宽(不太精确)
         * <p>
         * 这个目前不是很好用,比如有数字就会导致换行。而且长度也不是刚好和实际长度一致。 所以需要精确到刚好列宽的慎用。 当然也可以自己参照
         * {@link LongestMatchColumnWidthStyleStrategy}重新实现.
         * <p>
         * poi 自带{@link SXSSFSheet#autoSizeColumn(int)} 对中文支持也不太好。目前没找到很好的算法。 有的话可以推荐下。
         *
         * <p>
         * 1. 创建excel对应的实体对象 参照{@link LongestMatchColumnWidthData}
         * <p>
         * 2. 注册策略{@link LongestMatchColumnWidthStyleStrategy}
         * <p>
         * 3. 直接写即可
         */
        @Test
        public void longestMatchColumnWidthWrite() {
            String fileName =
                TestFileUtil.getPath() + "longestMatchColumnWidthWrite" + System.currentTimeMillis() + ".xlsx";
            // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
            EasyExcel.write(fileName, LongestMatchColumnWidthData.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("模板").doWrite(dataLong());
        }
    
        private List<LongestMatchColumnWidthData> dataLong() {
            List<LongestMatchColumnWidthData> list = new ArrayList<LongestMatchColumnWidthData>();
            for (int i = 0; i < 10; i++) {
                LongestMatchColumnWidthData data = new LongestMatchColumnWidthData();
                data.setString("测试很长的字符串测试很长的字符串测试很长的字符串" + i);
                data.setDate(new Date());
                data.setDoubleData(1000000000000.0);
                list.add(data);
            }
            return list;
        }
    
    
        /**
         * 文件下载并且失败的时候返回json(默认失败了会返回一个有部分数据的Excel)
         *
         * @since 2.1.1
         */
        @GetMapping("downloadFailedUsingJson")
        public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
            // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
            try {
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("utf-8");
                // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
                String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\+", "%20");
                response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
                // 这里需要设置不关闭流
                EasyExcel.write(response.getOutputStream(), DownloadData.class).autoCloseStream(Boolean.FALSE).sheet("模板")
                    .doWrite(data());
            } catch (Exception e) {
                // 重置response
                response.reset();
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                Map<String, String> map = new HashMap<String, String>();
                map.put("status", "failure");
                map.put("message", "下载文件失败" + e.getMessage());
                response.getWriter().println(JSON.toJSONString(map));
            }
        }
    
    /**
     * 样式的数据类
     *
     * @author Jiaju Zhuang
     **/
    @Data
    // 头背景设置成红色 IndexedColors.RED.getIndex()
    @HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 10)
    // 头字体设置成20
    @HeadFontStyle(fontHeightInPoints = 20)
    // 内容的背景设置成绿色 IndexedColors.GREEN.getIndex()
    @ContentStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 17)
    // 内容字体设置成20
    @ContentFontStyle(fontHeightInPoints = 20)
    public class DemoStyleData {
        // 字符串的头背景设置成粉红 IndexedColors.PINK.getIndex()
        @HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 14)
        // 字符串的头字体设置成20
        @HeadFontStyle(fontHeightInPoints = 30)
        // 字符串的内容的背景设置成天蓝 IndexedColors.SKY_BLUE.getIndex()
        @ContentStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 40)
        // 字符串的内容字体设置成20
        @ContentFontStyle(fontHeightInPoints = 30)
        @ExcelProperty("字符串标题")
        private String string;
        @ExcelProperty("日期标题")
        private Date date;
        @ExcelProperty("数字标题")
        private Double doubleData;
    }
    
        /**
         * 注解形式自定义样式
         * <p>
         * 1. 创建excel对应的实体对象 参照{@link DemoStyleData}
         * <p>
         * 3. 直接写即可
         *
         * @since 2.2.0-beta1
         */
        @Test
        public void annotationStyleWrite() {
            String fileName = TestFileUtil.getPath() + "annotationStyleWrite" + System.currentTimeMillis() + ".xlsx";
            // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
            EasyExcel.write(fileName, DemoStyleData.class).sheet("模板").doWrite(data());
        }
    
        /**
         * 自定义样式
         * <p>1. 创建excel对应的实体对象 参照{@link DemoData}
         * <p>2. 创建一个style策略 并注册
         * <p>3. 直接写即可
         */
        @Test
        public void styleWrite() {
            String fileName = TestFileUtil.getPath() + "styleWrite" + System.currentTimeMillis() + ".xlsx";
            // 头的策略
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 背景设置为红色
            headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short)20);
            headWriteCellStyle.setWriteFont(headWriteFont);
            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
            contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
            // 背景绿色
            contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
            WriteFont contentWriteFont = new WriteFont();
            // 字体大小
            contentWriteFont.setFontHeightInPoints((short)20);
            contentWriteCellStyle.setWriteFont(contentWriteFont);
            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    
            // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
            EasyExcel.write(fileName, DemoData.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("模板")
                .doWrite(data());
        }
    
  • 相关阅读:
    10 个非常有用的 AngularJS 框架
    15个最新加速 Web 开发的框架和工具
    最新13个加速 Web 开发的框架和工具
    7款个性化jQuery/HTML5地图插件
    19款绚丽实用的jQuery/CSS3侧边栏菜单
    7 个顶级的 HTML5 Canvas 动画赏析
    10款精美的web前端源码的特效
    10款web前端基于html5/CSS3应用特效
    8个强大的基于Bootstrap的CSS框架
    7款经典炫酷的HTML5/jQuery动画应用示例及源码
  • 原文地址:https://www.cnblogs.com/land-fill/p/14928743.html
Copyright © 2011-2022 走看看