使用 ClosedXML,我需要显示 10(基数),上标为 2。 因此它是一个指数值。我知道我可以通过以下方式制作 2 的下标:
ws.Cell(2, 8).Value = 2;
ws.Cell(2, 8).Style.Font.VerticalAlignment = XLFontVerticalTextAlignmentValues.Superscript;
但是如何显示 10(与上标值位于同一单元格中的基数)? 本质上我试图在同一个单元格中显示两种不同风格的字体。 希望这是有道理的。
我尝试使用以下内容,但没有走得太远,因为它显示 102 而不是 2 作为上标:
ws.Cell(2, 8).Value = 102;
ws.Cell(rw, 8).RichText.Substring(2).VerticalAlignment = XLFontVerticalTextAlignmentValues.Superscript;
这似乎是Excel本身的问题。在 Excel 中,如果单元格的内容是数字,我无法将
2
设置为上标。将内容更改为'102
以强制其为文本后,它起作用了。
在 ClosedXML 中也同样有效:
ws.Cell(2, 8).Value = "'102";
ws.Cell(rw, 8).RichText.Substring(2).VerticalAlignment = XLFontVerticalTextAlignmentValues.Superscript;
我注意到之前的答案不再有效。在 ClosedXML 中向单元格添加富文本的界面已经更改(我相信从版本 0.100 开始)。
IXLCell.CreateRichText
将单元格的值替换为富文本对象。此方法返回富文本对象,允许您将方法链接到它,如下所示:
// Method 1: Add rich text by chaining methods
ws.Cell("A1").CreateRichText()
.AddText("Some BOLD Text").SetFontColor(XLColor.Red)
.AddText("with superscript").SetVerticalAlignment(XLFontVerticalTextAlignmentValues.Superscript)
.AddText("and some bold and italic").SetBold().SetItalic()
;
IXLCell.GetRichText
来获取富文本对象。这使得动态样式更加灵活。
在下面的代码中,如果关联的颜色是“Bole”,我们将文本格式化为下标。
// List of (text, color)-tuples for demonstration
var textColorTuples = new List<(string, XLColor)>{
("Aqua ", XLColor.Aqua),
("CarminePink ", XLColor.CarminePink),
("Bole ", XLColor.Bole),
("PinkOrange ", XLColor.PinkOrange),
};
// Method 2: Add rich text object to cell, then later
var cell = ws.Cell("A2");
cell.CreateRichText();
foreach((var text, var color) in textColorTuples){
if (color == XLColor.Bole){ // Styling rich text conditionally
cell.GetRichText().AddText(text).SetFontColor(color).SetBold().SetVerticalAlignment(XLFontVerticalTextAlignmentValues.Subscript);
}
else{
cell.GetRichText().AddText(text).SetFontColor(color).SetBold();
}
}