1 year ago
#306770
Flo_Maxl
How to get correct HSSFFont .IsBold Value for first Char in HSSFRichTextString using NPOI?
I was coding a function that has a HSSFCell as input and returns the input of the cell formated with .xml tags ( etc.) in order to do so I iterate trough the HSSFRichTextString and check the font for each character. Everything works as expected as long as the first character in the cell is not bold. Somehow HSSFFont.IsBold is always sending a false even if the first char is bold. Same behavior for .IsItalic
I testet the following cases:
Case 1:
- Cell Value:"My name is Flo"
- Return:"M
<Bold>
y nam</Bold>
e is Flo" - This is the correct Output.
Case 2:
- Cell Value:"My name is Flo"
- Return:"My name is Flo"
- Font.IsBold doesnt recognice the first and the following letters as bold.
Case 3:
- Cell Value:" My name is Flo"
- Return:"
<Bold>
My nam</Bold>
e is Flo" - It works if the first Character is a " ".
Case 4:
- Cell Value:" My name is Flo"
- Return:" My name is
<Bold>
Flo</Bold>
" - It doesn not work for the section including the first char, but for the rest.
I dont know if someone came across this issue or is aber to help me but this would be great. Thanks alot guys.
Here is the funktion I created:
private string cellFormatterHSSF (HSSFCell hssfCell, HSSFWorkbook hssfwb)
{
try
{
HSSFRichTextString rts = (HSSFRichTextString)hssfCell.RichStringCellValue;
string value = rts.ToString();
StringBuilder sb = new StringBuilder();
Boolean bold = false;
Boolean italic = false;
for (int i = 1; i < rts.Length; i++)
{
HSSFFont font = (HSSFFont)hssfwb.GetFontAt(rts.GetFontAtIndex(i));
if (font.IsBold && font.IsItalic && !bold && !italic)
{
sb.Append("<BOLD>");
sb.Append("<ITALIC>");
sb.Append(value[i]);
bold = true;
italic = true;
continue;
}
else if (font.IsItalic && !italic)
{
sb.Append("<ITALIC>");
sb.Append(value[i]);
italic = true;
}
else if (font.IsBold && !bold)
{
sb.Append("<BOLD>");
sb.Append(value[i]);
bold = true;
}
else if (!font.IsItalic && italic && !font.IsBold && bold)
{
sb.Append("</ITALIC>");
sb.Append("</BOLD>");
sb.Append(value[i]);
bold = false;
italic = false;
continue;
}
else if (!font.IsBold && bold)
{
sb.Append("</BOLD>");
sb.Append(value[i]);
bold = false;
}
else if (!font.IsItalic && italic)
{
sb.Append("</ITALIC>");
sb.Append(value[i]);
italic = false;
}
else
sb.Append(value[i]);
}
if (bold)
{
sb.Append("</BOLD>");
}
if (italic)
{
sb.Append("</ITALIC>");
}
return rankFormatter(sb.ToString());
}
catch (Exception)
{
return string.Empty;
}
}
c#
excel
apache-poi
npoi
hssf
0 Answers
Your Answer