Sobhan Sobhan - 1 month ago 21
C# Question

Copy HSSFCellStyle to XSSFCellStyle in NPOI

My input file is .xls from where I have to read data, manipulate and write back to .xlsx file along with the styles.

So, using NPOI HSSF to read from .xls and NPOI XSSF to generate the .xlsx file.
I am done with the data. But I have to copy the cell formats from the .xls and apply to the output file.

When I write

outputheaderStyle.CloneStyleFrom(inputheaderStyle);
an exception occurs as inputheaderStyle is of type HSSFCellStyle and outputheaderStyle is of type XSSFCellStyle


Can only clone from one XSSFCellStyle to another, not between
HSSFCellStyle and XSSFCellStyle


outputheaderStyle.CloneStyleFrom((XSSFCellStyle)inputheaderStyle);


throws exception


Unable to cast object of type 'NPOI.HSSF.UserModel.HSSFCellStyle' to
type 'NPOI.XSSF.UserModel.XSSFCellStyle'


Is there any other way to copy the style?

Answer

Well, the cell style of .xls file is HSSFCellStyle and for .xlsx file it is XSSFCellStyle. Currently there is no direct way to convert the HSSFCellStyle to XSSFCellStyle in NPOI.

I managed my program by copying one by one style individually.

_xssfStyle .BorderLeft = _hssfStyle .BorderLeft;
_xssfStyle .BorderRight = _hssfStyle .BorderRight;
_xssfStyle .BorderTop = _hssfStyle .BorderTop;
_xssfStyle .BorderBottom = _hssfStyle .BorderBottom;
_xssfStyle .FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
_xssfStyle .FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
_xssfStyle .WrapText = _hssfStyle .WrapText;
_xssfStyle .VerticalAlignment = _hssfStyle .VerticalAlignment;
Comments