Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何检查是否可以从文件流构造IWorkbook对象?_C#_.net_Excel_Npoi - Fatal编程技术网

C# 如何检查是否可以从文件流构造IWorkbook对象?

C# 如何检查是否可以从文件流构造IWorkbook对象?,c#,.net,excel,npoi,C#,.net,Excel,Npoi,我使用NPOI库读取xlsx和xls文件 我有以下代码: IWorkbook workBook = null; string fileExtension = Path.GetExtension(path); using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { if (fileExtension == ".xls") workBook = new HSSFWorkbook(fs);

我使用NPOI库读取xlsx和xls文件

我有以下代码:

IWorkbook workBook = null;
string fileExtension = Path.GetExtension(path);
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    if (fileExtension == ".xls")
        workBook = new HSSFWorkbook(fs);
    else if (fileExtension == ".xlsx")
        workBook = new XSSFWorkbook(fs);
}
这是完美的工作。 但是,excel文件的
路径
并不总是在其名称中包含扩展名(.xls或.xlsx)

因此,我需要检查
fs
是否适用于
HSSFWorkbook()
XSSFWorkbook()


知道在没有文件扩展名的情况下如何检查它吗?

应用来自的文件头信息,我们可以使用以下方法:

public static class FormatRecognizer
{
    public static Boolean IsZipFile(Stream stream)
    {
        if (stream == null)
            throw new ArgumentNullException(paramName: nameof(stream));

        var zipHeader = new Byte[]
        {
            0x50, 0x4B, 0x03, 0x04
        };

        var streamBytes = GetBytesAndRestore(stream, zipHeader.Length);
        return streamBytes.SequenceEqual(zipHeader);
    }


    public static Boolean IsOffice2003File(Stream stream)
    {
        if (stream == null)
            throw new ArgumentNullException(paramName: nameof(stream));

        var officeHeader = new Byte[]
        {
            0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1,
        };

        var streamBytes = GetBytesAndRestore(stream, officeHeader.Length);
        return streamBytes.SequenceEqual(officeHeader);
    }


    private static IEnumerable<Byte> GetBytesAndRestore(Stream stream, Int32 bytesCount)
    {
        if (stream == null)
            throw new ArgumentNullException(paramName: nameof(stream));

        var position = stream.Position;
        try
        {
            using (var reader = new BinaryReader(stream, Encoding.Default, leaveOpen: true))
            {
                return reader.ReadBytes(bytesCount);
            }
        }
        finally
        {
            stream.Position = position;
        }
    }
}

它不是绝对可靠的,因为对于简单的zip存档,
IsZipFile
将返回true,而对于doc、ppt等,
isofice2003file
也将成功

但这是我能想到的最简单的解决办法。任何更正确的内容都需要对文件格式有更深入的了解,这可能是您所需要的,也可能不是您所需要的

            IWorkbook workBook = null;
            string fileExtension = Path.GetExtension(path);

            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                workBook = WorkbookFactory.Create(fs);
            }

WorkbookFactory.Create()方法根据从xls或xlsx文件生成的fileStreem参数构造IWorkbook。

未对其进行测试,但在打开类似于HSSFWorbook的*.xlsx时,NPOI不会引发任何异常?
PrintFormatInfo("1.txt");
PrintFormatInfo("1.xls");
PrintFormatInfo("1.xlsx");
            IWorkbook workBook = null;
            string fileExtension = Path.GetExtension(path);

            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                workBook = WorkbookFactory.Create(fs);
            }