如何使用C#和Excel Interop获取Excel文件创建日期等属性
使用C#和Excel Interop获取Excel文件的创建日期
嘿,你找错属性集合啦!你现在拿到的CustomDocumentProperties是用来存储用户自定义属性的,而Excel文件的创建日期属于内置文档属性,得用Workbook.BuiltinDocumentProperties来获取才行。下面给你详细讲两种可行的方法,还有一些注意事项:
方法一:通过Excel内置文档属性(推荐,获取文档内部存储的创建日期)
创建日期对应的内置属性名称是"Creation Date",你可以通过名称或者枚举值来获取,后者更不容易出错:
通过属性名称获取
using Microsoft.Office.Interop.Excel; using System.Linq; // 假设你已经初始化并打开了Workbook实例myworkbook var builtInProps = myworkbook.BuiltinDocumentProperties as DocumentProperties; if (builtInProps != null) { // 先检查属性是否存在,避免直接索引抛出异常 var creationDateProp = builtInProps.Cast<DocumentProperty>() .FirstOrDefault(p => p.Name == "Creation Date"); if (creationDateProp != null) { DateTime creationDate = Convert.ToDateTime(creationDateProp.Value); Console.WriteLine($"Excel文档内部创建日期:{creationDate:yyyy-MM-dd HH:mm:ss}"); } else { Console.WriteLine("未找到创建日期属性"); } }
通过内置属性枚举值获取(更安全)
这种方式需要引用Microsoft.Office.Core程序集,用MsoDocProperties枚举来定位属性,避免拼写错误:
using Microsoft.Office.Interop.Excel; using Microsoft.Office.Core; var builtInProps = myworkbook.BuiltinDocumentProperties as DocumentProperties; if (builtInProps != null) { try { var creationDateProp = builtInProps[MsoDocProperties.msoPropertyIDCreateDate]; DateTime creationDate = Convert.ToDateTime(creationDateProp.Value); Console.WriteLine($"Excel文档内部创建日期:{creationDate:yyyy-MM-dd HH:mm:ss}"); } catch (Exception ex) { Console.WriteLine($"获取创建日期失败:{ex.Message}"); } }
方法二:直接从文件系统获取(无需打开Excel)
如果你不需要文档内部存储的创建日期,只是想获取文件在操作系统中的创建时间,可以用FileInfo来快速获取,这种方式不需要加载Excel,效率更高:
using System.IO; string excelPath = @"D:\YourFile.xlsx"; var fileInfo = new FileInfo(excelPath); DateTime systemCreationDate = fileInfo.CreationTime; Console.WriteLine($"文件系统创建日期:{systemCreationDate:yyyy-MM-dd HH:mm:ss}");
⚠️ 注意:这个日期是文件在当前系统中的创建时间,如果文件被复制、移动,这个日期会改变,但Excel文档内部的创建日期还是原始值,按需选择即可。
一些关键注意事项
- 用完Excel Interop对象后,一定要记得释放COM资源,避免内存泄漏:
Marshal.ReleaseComObject(creationDateProp); Marshal.ReleaseComObject(builtInProps); myworkbook.Close(); Marshal.ReleaseComObject(myworkbook); excelApp.Quit(); Marshal.ReleaseComObject(excelApp); - 确保你引用了正确的程序集:
Microsoft.Office.Interop.Excel和Microsoft.Office.Core(可以通过NuGet安装Microsoft.Office.Interop.Excel包)。 - 访问属性时尽量做存在性检查或捕获异常,某些特殊格式的Excel文件可能缺少部分内置属性。
内容的提问来源于stack exchange,提问作者Suslik
相关产品推荐
相关产品推荐

