richText 单元格中的自定义对齐方式 Exceljs

Custom alignment in richText cells Exceljs

"exceljs": "^3.9.0"

我需要创建一个电子表格,其中的单元格具有 2 个不同的值,如下所示。 第一个值需要左对齐,第二个值需要右对齐。

我现在的结果是:

这是没有“/”的单元格的 richText“

    [
  {
    "font": {
      "size": 8,
      "name": "Arial"
    },
    "alignment": {
      "vertical": "middle",
      "horizontal": "distributed"
    },
    "text": "392.3 "
  },
  {
    "font": {
      "color": {
        "argb": "00c90a00"
      },
      "size": 8,
      "name": "Arial"
    },
    "alignment": {
      "vertical": "middle",
      "horizontal": "distributed"
    },
    "text": " -10%"
  }
]

以及带有“/”的单元格的 richText

    [
  {
    "font": {
      "size": 8,
      "name": "Arial"
    },
    "alignment": {
      "vertical": "middle",
      "horizontal": "distributed"
    },
    "text": "392.3 "
  },
  {
    "font": {
      "size": 8,
      "name": "Arial"
    },
    "alignment": {
      "vertical": "middle",
      "horizontal": "distributed"
    },
    "text": " / "
  },
  {
    "font": {
      "color": {
        "argb": "00c90a00"
      },
      "size": 8,
      "name": "Arial"
    },
    "alignment": {
      "vertical": "middle",
      "horizontal": "distributed"
    },
    "text": " -10%"
  }
]

是否可以像第一个屏幕截图那样做?

Is it possible to do what the first screenshot looks like?

是的,这是可能的,但您无法在同一单元格中以不同方式对齐文本。它不适用于 Excel 本身,因此绝对不适用于 ExcelJS!有数百篇文章询问有关 Excel 的问题,但有一句话一语中的:

Unlike Word, Excel does not have the concept of paragraphs within a cell. Horizontal and vertical alignment apply to a cell as a whole.

引自用户 Hansv MVP from this thread.

您可以通过不同的途径来处理该项目,这取决于最适合您的途径:

  • Split the cells with the data. ExcelJS does has the .spliceRows() function,因此您可以使用它(在各个单元格上使用 RichText 格式)。
  • 您可以从一开始就实现写入逻辑,即在一个单元格中实现数据的一部分,然后在单元格中实现下一部分,依此类推。之后,您可以 to color the border 将相邻数据设置为背景颜色,从而使其消失。

我强烈推荐第二种方法。在我看来,这应该是最简单的解决方案,因为您可以正确地设置一个“格式化逻辑”,从这个意义上来说,您可以自由地使用您正在编写的每个值。