Sobhan Sobhan - 1 year ago 375
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

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


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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download