gpt4 book ai didi

c# - NPOI:创建一个包含两个不同大小字符串的单元格

转载 作者:行者123 更新时间:2023-12-04 21:38:11 25 4
gpt4 key购买 nike

如标题所示,我想在包含 2 个字符串的 NPOI 2.1.3-Workbook 中创建一个单元格:一个“正常”大小的字符串和一个“小”大小的字符串。 => 我想更改部分单元格的字体大小。

到目前为止我的代码:

var planCell = planRow.CreateCell(lineCnt + 1);

var planCellStyle = workbook.CreateCellStyle();
planCellStyle.WrapText = true;
planCellStyle.VerticalAlignment = VerticalAlignment.Top;
planCellStyle.Alignment = HorizontalAlignment.Left;
var font = workbook.CreateFont();
font.FontName = HSSFFont.FONT_ARIAL;
font.FontHeightInPoints = 16;
font.Boldweight = (short)FontBoldWeight.Bold;
planCellStyle.SetFont(font);
planCell.CellStyle = planCellStyle;

string planTitleContent = string.Empty;
... (some logic to get desired string for planTitleContent)

string planInfoContent = string.Empty;
... (some logic to get desired string for planInfoContent)

planCell.SetCellValue(planTitleContent + "\n\n"+planInfoContent);

准确地说,我希望“planInfoContent”部分以比“planCellContent”部分更小的字体大小显示。我搜索了很多,但我只是找到了适用于整个单元格的 CellStyle 值。所以我希望我错过了两个单元格的东西并不是一个真正的选择。

最佳答案

只是我自己想通了:)

首先,创建 2 种所需格式的字体(为了我和简单起见,只有字体大小是相关的):

var font1 = excel.CreateFont();
font1.FontName = HSSFFont.FONT_ARIAL;
font1.FontHeightInPoints = 12;
font1.Boldweight = (short)FontBoldWeight.Normal;

var font2 = excel.CreateFont();
font2.FontName = HSSFFont.FONT_ARIAL;
font2.FontHeightInPoints = 8;
font2.Boldweight = (short)FontBoldWeight.Normal;

然后,在获得字符串后,使用 (N)POI applyFont -方法。

它在 NPOI 中的实现之一具有以下签名:
applyFont(int startIndex, int endIndex, IFont font)
所以现在,有字符串 planTitleContent和字符串 planInfoContent ,剩下的步骤非常明显:只需创建 IRichTextString 的实例并通过构造函数参数将您的字符串添加到其中。然后,通过索引应用想要的字体,如下所示:
IRichTextString formattedCellContent = new HSSFRichTextString(planTitleContent + "\n"+planInfoContent);
richString.ApplyFont(0, planTitleContent.Length, font1);
richString.ApplyFont(planTitleContent.Length + 1, (planTitleContent + "\n" + planInfoContent).Length, font2);

planCell.SetCellValue(formattedCellContent);

所以,这对我来说就像一个魅力。希望它可以帮助其他人!

关于c# - NPOI:创建一个包含两个不同大小字符串的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28231732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com