读取Excel文件的版本

时间:2024-04-21 16:25:03

读取xls文件和xlsx文件创建的版本号。

虽然xlsx声明的是向前兼容,但是不知道OleDb是不是也是这样,没有办法所以要读取文件版本,限定只能读取Excel2007保存的文件。

 using ICSharpCode.SharpZipLib.Zip;

 public const ushort BIFF8 = 0x0600;
public const ushort BIFF7 = 0x0500;
public static string GetExcelVersion(string fileName)
{
string version = string.Empty;
try
{
if (Path.GetExtension(fileName) == ".xls")
{
BinaryReader binReader = new BinaryReader(File.Open(fileName, FileMode.Open));
try
{
byte[] testArray = new byte[];
int count = binReader.Read(testArray, , ); if (count != )
{
// Reset the position in the stream to zero.
binReader.BaseStream.Seek(, SeekOrigin.Begin);
byte[] testArray2 = new byte[];
int count2 = binReader.Read(testArray2, , );
ushort BOF = binReader.ReadUInt16();
ushort Length = binReader.ReadUInt16();
ushort Version = binReader.ReadUInt16();
ushort file = binReader.ReadUInt16();
if (Version == BIFF8)
{
version = "Excel8.0";
}
if (Version == BIFF7)
{
version = "Excel8.0";
}
}
}
catch (EndOfStreamException e)
{
throw e;
}
finally
{
binReader.Close();
}
}
else if (Path.GetExtension(fileName) == ".xlsx")
{
ZipFile zip = new ZipFile(fileName);
try
{
IEnumerator entries = zip.GetEnumerator();
while (entries.MoveNext())
{
ZipEntry current = (ZipEntry)entries.Current;
if (current.Name.Equals("docProps/app.xml"))
{
Stream stream = zip.GetInputStream(current);
XPathNavigator navigator = new XPathDocument(stream).CreateNavigator();
XmlNamespaceManager resolver = new XmlNamespaceManager(navigator.NameTable);
resolver.AddNamespace("x", "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties");
XPathNodeIterator iterator = navigator.Select("//x:AppVersion", resolver);
iterator.MoveNext();
string attribute = iterator.Current.InnerXml;
version = attribute;
}
}
}
catch (IOException ioEx)
{
throw ioEx;
}
finally
{
if (zip != null)
{
zip.Close();
}
}
}
}
catch (IOException ioEx)
{
throw ioEx;
} return version;
}

调用:

   catch
{
try
{
string version = GetExcelVersion(FilePath);
string error = string.Empty;
if (version == "")
{
error = "无法识别的Excel文件,请确保文件为有效的Excel2003或者Excel2007格式文件。";
}
else if (!version.Contains("") && !version.Contains("Excel8.0"))
{
error = string.Format("由高版本的Excel程序创建,请转换为Excel2003或者Excel2007格式文件", version);
}
throw new InvalidDataException(error);
}
catch (IOException ioEx)
{
throw ioEx;
}
}