简体   繁体   English

用于阅读 XLS 的 NPOI

[英]NPOI for reading XLS

I am working on some project where I use NPOI library for reading some data from excel.我正在一些项目中使用 NPOI 库从 excel 中读取一些数据。 Everything was working good but then I tried to read .xls and it stopped working.一切正常,但后来我尝试阅读 .xls 并停止工作。 (Everything was well for .xlsx). (.xlsx 一切正常)。

The last thing i tried is this:我尝试的最后一件事是:

 IWorkbook hssfwb;
                using (FileStream file = new FileStream(@filePath, FileMode.Open, FileAccess.Read))
                {
                     hssfwb = WorkbookFactory.Create(file);
                }

The exception I get is:我得到的例外是:

Your stream was neither an OLE2 stream, nor an OOXML stream.您的流既不是 OLE2 流,也不是 OOXML 流。

What I need is a way to open .xls files using NPOI library.我需要的是一种使用 NPOI 库打开 .xls 文件的方法。 Thanks in advance.提前致谢。

To operate with the old Excel 97-2003 format (Files ending with ".xls"), you can use the HSSFWorkbook class.要使用旧的 Excel 97-2003 格式(以“.xls”结尾的文件),您可以使用HSSFWorkbook类。

If you check the file name's extension, you can handle both file types when reading the file into a IWorkbook model:如果检查文件名的扩展名,则可以在将文件读入IWorkbook模型时处理这两种文件类型:

        MemoryStream fileStream = new MemoryStream(fileContent);
        IWorkbook workbook = null;

        if (fileName.ToLower().EndsWith(".xlsx"))
        {
            // new OOXML format
            workbook = new XSSFWorkbook(fileStream);
        }
        else
        {
            // old Excel 97 format
            workbook = new HSSFWorkbook(fileStream);
        }

From ther on you can handle the content of the spreadsheet as usual:从那时起,您可以像往常一样处理电子表格的内容:

        // get first sheet
        ISheet sheet = workbook.GetSheetAt(0);

        // get header names as string array
        IRow headerRow = sheet.GetRow(rowNumber);
        List<ICell> headerCells = headerRow.Cells;
        List<string> rowData = new List<string>();
        foreach (ICell cell in headerCells)
        {
            rowData.Add(cell.ToString());
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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