NPOI:创build一个包含两个不同大小string的单元格

所以如题目所示,我想在一个包含2个string的NPOI 2.1.3-Workbook中创build一个单元格:一个“普通”大小的string和一个“小”大小的string。 =>我想改变单元的一部分的字体大小。

我的代码到目前为止:

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”部分更小的字体显示。 我search了很多,但我只是find适用于整个单元格的CellStyle值。 所以我希望我缺less两个单元格的东西并不是真正的select。

只是想出了自己:)

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

 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; 

然后,在得到你的string之后,利用(N)POI applyFont -Method 。

在NPOI中的一个实现有以下签名:

applyFont(int startIndex, int endIndex, IFont font)

所以现在,有了stringplanTitleContent和stringplanInfoContent ,其余的步骤是非常明显的:只需创build一个IRichTextString的实例,并通过构造函数参数添加您的string。 然后,像这样通过索引应用想要的字体:

 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); 

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