Search code examples
c#.net-8.0

ICSharpCode.SharpZipLib.Zip.ZipException: 'EOF in header'


I am using DotNetCore.NPOI Version 1.2.3 to read an excel file.

My excel file is a simple one with a header row with about 4 columns and about 90 records. But I continue getting the error message ICSharpCode.SharpZipLib.Zip.ZipException: 'EOF in header'. Any ideas/suggestions?

My code is like below:

public static void ReadFile()
{
    const string filePath = "D://MyFile.xlsx";
    if (!File.Exists(filePath))
    {
        return;
    }

    var sFileExtension = Path.GetExtension(filePath);

    using var stream = new FileStream(filePath, FileMode.Create);
    stream.Position = 0;

    ISheet sheet;
    if (sFileExtension == ".xls")
    {
        var hssfWb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats   
        sheet = hssfWb.GetSheetAt(0); //get first sheet from workbook   
    }
    else
    {
        var xssfWb = new XSSFWorkbook(stream); //This will read 2007 Excel format   
        sheet = xssfWb.GetSheetAt(0); //get first sheet from workbook    
    }

    var headerRow = sheet.GetRow(0); //Get Header Row 
    int cellCount = headerRow.LastCellNum;

    for (var i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File 
    {
        var row = sheet.GetRow(i);

        if (row == null)
        {
            continue;
        }

        if (row.Cells.All(d => d.CellType == CellType.Blank))
        {
            continue;
        }

        for (int j = row.FirstCellNum; j < cellCount; j++)
        {
            if (row.GetCell(j) != null)
            {
                Console.WriteLine($"Cell Value {j}: {row.GetCell(j)}");
            }
        }
    }
}

Solution

  • Why are you using FileMode.Create instead of FileMode.Open in FileStream call? It truncates the file if it exists or creates a new one if it doesn’t.

    using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);