博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jxl 操作模板,自适应高度HssfCellStyle 自适应。
阅读量:7192 次
发布时间:2019-06-29

本文共 4351 字,大约阅读时间需要 14 分钟。

hot3.png

一:HSSFCellStyle

// 生成一个样式

HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中 
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中

 // 背景色

style.setFillForegroundColor(HSSFColor.YELLOW.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
style.setFillBackgroundColor(HSSFColor.YELLOW.index); 

// 设置边框

style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
// 自动换行  这种换行的样式是这样的:

095234_BXes_1052786.png

style.setWrapText(true);  

// 生成一个字体

HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 10);
font.setColor(HSSFColor.RED.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("宋体");

// 把字体 应用到当前样式

style.setFont(font);

//style设置好后,为cell设置样式

cell.setCellStyle(style)//cell为已有的单元格

二:

  在Excel处理的过程中,可能有需要用到行高自适应的时候。

  下面贴出用POI实现Excel行高自适应的代码。
  该代码可以处理一行Excel按内容自适应高度。可以处理一行内的合并单元格。
  但是该代码不支持涉及多行合并单元的计算,以后有空再补上。多行合并单元格的高度获取比较容易,但是其高度自适应就比较麻烦了。
  上代码:

/**

     * 根据行内容重新计算行高
     * row
     */
    public static void calcAndSetRowHeigt(HSSFRow sourceRow) {
        //原行高
        short height = sourceRow.getHeight();
        //计算后的行高
        double maxHeight = height;
        for (int cellIndex = sourceRow.getFirstCellNum(); cellIndex <= sourceRow.getPhysicalNumberOfCells(); cellIndex++) {
            HSSFCell sourceCell = sourceRow.getCell(cellIndex);
            //单元格的内容
            String cellContent = getCellContentAsString(sourceCell);
            if(null == cellContent || "".equals(cellContent)){
                continue;
            }
            //单元格的宽度
            int columnWidth = getCellWidth(sourceCell);
            System.out.println("单元格的宽度 : " + columnWidth + "    单元格的高度 : " + maxHeight + ",    单元格的内容 : " + cellContent);
            HSSFCellStyle cellStyle = sourceCell.getCellStyle();
            HSSFFont font = cellStyle.getFont(sourceRow.getSheet().getWorkbook());
            //字体的高度
            short fontHeight = font.getFontHeight();
            
            //cell内容字符串总宽度
            double cellContentWidth = cellContent.getBytes().length * 2 * 256;
            
           //字符串需要的行数 不做四舍五入之类的操作
           double stringNeedsRows =(double)cellContentWidth / columnWidth;
           //小于一行补足一行
           if(stringNeedsRows < 1.0){
               stringNeedsRows = 1.0;
           }
           
           //需要的高度             (Math.floor(stringNeedsRows) - 1) * 40 为两行之间空白高度
           double stringNeedsHeight = (double)fontHeight * stringNeedsRows;
           if(stringNeedsHeight > maxHeight){
               maxHeight = stringNeedsHeight;
           }
           System.out.println("字体高度 : " + fontHeight + ",    字符串宽度 : " + cellContentWidth + ",    字符串需要的行数 : " + stringNeedsRows + ",   需要的高度 : " + stringNeedsHeight);
           System.out.println();
        }
        //超过原行高三倍 则为3倍 实际应用中可
        if(maxHeight/height > 5){
            maxHeight = 5 * height;
        }
        //最后取天花板防止高度不够
        maxHeight = Math.ceil(maxHeight);
        sourceRow.setHeight((short)maxHeight);
    }
    
    /**
     * 解析一个单元格得到数据
     * columnNameList
     * row
     * ext2
     * ext1
     * @return
     */
    private static String getCellContentAsString(HSSFCell cell) {
        if(null == cell){
            return "";
        }
        String result = "";
        switch (cell.getCellType()) {
        case Cell.CELL_TYPE_NUMERIC:
            String s = String.valueOf(cell.getNumericCellValue());
            if (s != null) {
                if (s.endsWith(".0")) {
                    s = s.substring(0, s.length() - 2);
                }
            }
            result = s;
            break;
        case Cell.CELL_TYPE_STRING:
            result = ToolKits.nulltoempty(String.valueOf(cell.getStringCellValue())).trim();
            break;
        case Cell.CELL_TYPE_BLANK:
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            result = String.valueOf(cell.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_ERROR:
            break;
        default:
            break;
        }
        return result;
    }
    
    /**
    * 获取单元格及合并单元格的宽度
    * @param sheet
    * @param row
    * @param column
    * @return
    */
    private static int getCellWidth(HSSFCell cell) {
        int result = 0;
        HSSFSheet sheet = cell.getSheet();
        int rowIndex = cell.getRowIndex();
        int columnIndex = cell.getColumnIndex();
        
        boolean isPartOfRegion = false;
        int firstColumn = 0;
        int lastColumn = 0;
        int firstRow = 0;
        int lastRow = 0;
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            Region ca = sheet.getMergedRegionAt(i);
            firstColumn = ca.getColumnFrom();
            lastColumn = ca.getColumnTo();
            firstRow = ca.getRowFrom();
            lastRow = ca.getRowTo();
            if (rowIndex >= firstRow && rowIndex <= lastRow) {
                if (columnIndex >= firstColumn && columnIndex <= lastColumn) {
                    isPartOfRegion = true;
                    break;
                }
            }
        }
        if(isPartOfRegion){
            for (int i = firstColumn; i <= lastColumn; i++) {
                result += sheet.getColumnWidth(i);
            }
        }else{
            result = sheet.getColumnWidth(columnIndex);
        }
        return result;
    }

经过上面的方法计算,这种更符合我的需求,貌似格式也没有损坏:

095353_wYwb_1052786.png

转载于:https://my.oschina.net/u/1052786/blog/909542

你可能感兴趣的文章
念数字(15)
查看>>
online_judge_1474
查看>>
python-*args与**kwagrs 动态形参使用说明
查看>>
CSS列表逆序
查看>>
javascript方法--bind()
查看>>
spring Cloud中,解决Feign/Ribbon整合Hystrix第一次请求失败的问题?
查看>>
Install fail! Error: [@@babel/runtime/core-js/object/keys]
查看>>
基于vue 的 UI框架 -- Mint UI
查看>>
redux-saga 异步流
查看>>
Mina入门实例(一)
查看>>
HTML基本标签
查看>>
AngularJs学习——实现数据绑定的三种方式
查看>>
Ubuntu 安装yii2 advanced版 遇到的坑
查看>>
UVA - 11400 Lighting System Design
查看>>
[HNOI2005]狡猾的商人
查看>>
剑指offer(二十三,二十四,二十五)最小的k个数,连续子数组的最大和,链表中环的入口节点...
查看>>
linux下面如何让一个软件/命令开机自启动
查看>>
P4306 [JSOI2010]连通数
查看>>
RegExp
查看>>
提升软件的用户体验
查看>>