2

I am tring to implement NPOI package to covert an XSL file into XSLX one. Here is my code:

var stream = new FileStream("path to xls file", FileMode.Open);
HSSFWorkbook xsl_Workbook = new HSSFWorkbook(stream); // Old format
XSSFWorkbook retVal = new XSSFWorkbook(); // New format
for (int i = 0; i < xsl_Workbook.NumberOfSheets; i++)
{
    **XSSFSheet xssfsheet = (XSSFSheet)xsl_Workbook.GetSheetAt(i);** // error line
    xssfsheet.CopyTo(retVal, xsl_Workbook.GetSheetName(i), true, true);
    MemoryStream mstream = new MemoryStream();
    retVal.Write(mstream);
    retVal.Close();
    bytes = new byte[mstream.Length];
    mstream.Read(bytes, 0, (int)mstream.Length);
    File.WriteAllBytes("path to newfile with ext xlsx", bytes);
    mstream.Close();
}

I am getting an error at the error line:

System.InvalidCastException: Unable to cast object of type 'NPOI.HSSF.UserModel.HSSFSheet' to type 'NPOI.XSSF.UserModel.XSSFSheet'

I am not a C# developer, I am addapting what I can find online. Plesae help.

Thanks

Mark
  • 4,535
  • 7
  • 39
  • 76
  • Where did you find this code? The error happens because `xsl_Workbook.GetSheetAt(i)` returns a `HSSFSheet` object, which can't just be cast to an `XSSFSheet` object. Does this help? [How to convert HSSFWorkbook to XSSFWorkbook using Apache POI?](https://stackoverflow.com/questions/7230819/how-to-convert-hssfworkbook-to-xssfworkbook-using-apache-poi) – Pranav Hosangadi Dec 22 '21 at 19:11
  • 1
    It's all Java code. Not sure I can addapt it, will try. – Mark Dec 22 '21 at 19:14
  • The idea there is to copy rows from the `HSSFSheet` to the `XSSFSheet` – Pranav Hosangadi Dec 22 '21 at 19:17
  • So, it cannot copy sheet to sheet. It has to be row by row, correct? – Mark Dec 23 '21 at 17:10
  • It would appear so from the accepted answer there. I am not familiar with Apache POI to write an actual answer for you here. – Pranav Hosangadi Dec 23 '21 at 18:31
  • This can help you: https://stackoverflow.com/a/41172690/2250152 – user2250152 Jan 10 '22 at 13:31

0 Answers0