[英]How to determine excel file type(.xlsx or .xlsm) from file data
My application needs to save a byte[] to disk, the issue is that I know it is an excel file but not what the correct file extension is.我的应用程序需要将一个 byte[] 保存到磁盘,问题是我知道它是一个 excel 文件,但不知道正确的文件扩展名是什么。 Is there a way I can tell if the file is.xls or.xlsx or.xlsm from the data itself?
有什么方法可以从数据本身判断文件是 .xls 还是 .xlsx 还是 .xlsm?
I ended up writing an extension method to determine the excel file type.我最终编写了一个扩展方法来确定 excel 文件类型。 This method is not perfect.
这种方法并不完美。 It will only correctly detect a.xlsm file if the file has a macro.
如果文件有宏,它只会正确检测 a.xlsm 文件。
private static string FindType(this byte[] file)
{
using(MemoryStream ms = new MemoryStream(file))
{
var zf = new ZipArchive(ms, ZipArchiveMode.Read);
if (zf.Entries.Any(e=>e.FullName.StartsWith("xl.")))
{
if (zf.Entries.Any(e=>e.FullName.Equals("xl/vbaProject.bin", StringComparison.InvariantCultureIgnoreCase)))
return ".xlsm";
else
return ".xlsx";
}
}
return string.Empty;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.