SheetJS 合并后的单元格不能正常显示边框

发布时间 2023-12-15 11:41:51作者: 流年sugar

原配置样式代码

/**
   * 设置单元格样式
   * @param worksheet 工作单元
   * @param firstRow 开始行
   * @param lastRow 结束行
   * @param firstCol 开始列
   * @param lastCol 结束列
   * @param font 字号
   * @param blod 是否加粗
   */
  setCellStyle(worksheet: WorkSheet, firstRow, lastRow, firstCol, lastCol, font, blod) {
    for (var i = firstRow; i <= lastRow; i++) {
      for (var j = firstCol; j <= lastCol; j++) {
        //根据单元格地址转换
        var cell = utils.encode_cell({ c: j, r: i });
        if (worksheet[cell]) {
          worksheet[cell].s = {
            font: {
              sz: font,
              bold: blod
            },
            alignment: {
              horizontal: 'center',
              vertical: 'center',
              wrapText: true
            },
            border: {
              top: { style: 'thin' },
              right: { style: 'thin' },
              bottom: { style: 'thin' },
              left: { style: 'thin' }
            }
          };
        } 
      }
    }
  }

原因

值一般放在合并前的第一个单元格中,合并后其他被合并的单元格cell是配置为空,根据以上代码是没有去设置被置空合并单元格的边框的

解决方式

将置空的单元格设置边框

 worksheet[cell] = {
            s: {
              border: {
                top: { style: 'thin' },
                right: { style: 'thin' },
                bottom: { style: 'thin' },
                left: { style: 'thin' }
              }
            },
            v: ''
          };
        }

注:v属性(单元格值)一定要设置,否则样式不生效

完整代码

/**
   * 设置单元格样式
   * @param worksheet 工作单元
   * @param firstRow 开始行
   * @param lastRow 结束行
   * @param firstCol 开始列
   * @param lastCol 结束列
   * @param font 字号
   * @param blod 是否加粗
   */
  setCellStyle(worksheet: WorkSheet, firstRow, lastRow, firstCol, lastCol, font, blod) {
    for (var i = firstRow; i <= lastRow; i++) {
      for (var j = firstCol; j <= lastCol; j++) {
        //根据单元格地址转换
        var cell = utils.encode_cell({ c: j, r: i });
        if (worksheet[cell]) {
          worksheet[cell].s = {
            font: {
              sz: font,
              bold: blod
            },
            alignment: {
              horizontal: 'center',
              vertical: 'center',
              wrapText: true
            },
            border: {
              top: { style: 'thin' },
              right: { style: 'thin' },
              bottom: { style: 'thin' },
              left: { style: 'thin' }
            }
          };
        } else {
          worksheet[cell] = {
            s: {
              border: {
                top: { style: 'thin' },
                right: { style: 'thin' },
                bottom: { style: 'thin' },
                left: { style: 'thin' }
              }
            },
            v: ''
          };
        }
      }
    }
    return worksheet;
  }