Pratik
Pratik

Reputation: 11

Read Excel using NPOI

I am trying to read excel[xls and xlsx] using NPOI,I am using following code, but it is giving 'Unable to Read entire header; 27 bytes Read; expected 512 bytes' while reading an 8KB xls file

    byte[] byteArray = Encoding.UTF8.GetBytes(filepath);
    MemoryStream stream = new MemoryStream(byteArray);
    MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(filepath ?? ""));

    NPOI.HSSF.UserModel.HSSFWorkbook hssfwb = default(HSSFWorkbook);
    hssfwb = new NPOI.HSSF.UserModel.HSSFWorkbook(stream1);
    Sheet sheet = hssfwb.GetSheetAt(0);
    DataTable dtinputExcel = new DataTable();

I have tried every possible code available on net for this error. Please guide me what's the errorless method to read and excel[xls/xlsx] of any size.

Upvotes: 1

Views: 7149

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129697

The problem is that the constructor of HSSFWorkbook is expecting a stream containing the contents of the spreadsheet file, while you are passing it a MemoryStream containing the name of the file. You should be using a FileStream to read the file and passing that stream to the HSSFWorkbook constructor.

Try it like this:

IWorkbook hssfwb;
using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
    hssfwb = new HSSFWorkbook(fs);
}

ISheet sheet = hssfwb.GetSheetAt(0);

Upvotes: 1

Related Questions