简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM