如何用C#和Aspose库打开C:\schedules下最新带时间戳的Excel文件?
基于时间戳找到并打开最新的Excel文件(C# + Aspose.Cells)
要实现这个需求,核心是筛选符合命名规则的文件、解析时间戳排序、用Aspose加载目标文件,具体步骤和代码如下:
1. 筛选符合命名格式的文件
先定位到C:\schedules目录,筛选出所有以Schedule_开头、.xls结尾,且中间是12位时间戳(YYYYMMDDHHMM)的文件。这里用正则表达式精准匹配文件名格式,避免误选无关文件。
2. 解析时间戳并找出最新文件
对每个符合格式的文件,提取文件名中的12位时间戳字符串,转换为DateTime对象,通过比较时间戳大小,锁定时间最新的文件。
3. 用Aspose.Cells打开目标文件
拿到最新文件的完整路径后,直接用Aspose.Cells的Workbook类加载文件,后续即可进行格式化美化操作。
完整代码示例
using System; using System.IO; using System.Text.RegularExpressions; using Aspose.Cells; class Program { static void Main() { string targetDir = @"C:\schedules"; string fileNamePattern = @"^Schedule_(\d{12})\.xls$"; Regex regex = new Regex(fileNamePattern); // 检查目录是否存在 if (!Directory.Exists(targetDir)) { Console.WriteLine("目标目录不存在"); return; } FileInfo latestFile = null; DateTime latestTimestamp = DateTime.MinValue; // 遍历目录下的所有xls文件 foreach (string filePath in Directory.GetFiles(targetDir, "*.xls")) { FileInfo fileInfo = new FileInfo(filePath); Match match = regex.Match(fileInfo.Name); // 验证文件名格式是否符合要求 if (match.Success) { string timestampStr = match.Groups[1].Value; // 解析12位时间戳为DateTime对象 if (DateTime.TryParseExact(timestampStr, "yyyyMMddHHmm", null, System.Globalization.DateTimeStyles.None, out DateTime currentTimestamp)) { // 比较时间戳,保留最新的文件 if (currentTimestamp > latestTimestamp) { latestTimestamp = currentTimestamp; latestFile = fileInfo; } } } } // 判断是否找到符合条件的文件 if (latestFile == null) { Console.WriteLine("未找到符合格式的Schedule文件"); return; } // 用Aspose.Cells打开最新文件 try { Workbook workbook = new Workbook(latestFile.FullName); Console.WriteLine($"成功打开最新文件:{latestFile.Name}"); // 这里添加格式化美化逻辑,示例:设置第一行标题加粗 Worksheet worksheet = workbook.Worksheets[0]; Style style = workbook.CreateStyle(); style.Font.IsBold = true; worksheet.Cells["A1:Z1"].ApplyStyle(style, new StyleFlag { FontBold = true }); // 可选:保存格式化后的文件 workbook.Save(Path.Combine(targetDir, $"Formatted_{latestFile.Name}")); } catch (Exception ex) { Console.WriteLine($"打开文件失败:{ex.Message}"); } } }
注意事项
- 确保已通过NuGet安装Aspose.Cells包:
Install-Package Aspose.Cells - 提前处理异常场景:目录不存在、无符合格式的文件、时间戳解析失败、文件打开异常等
- 若需区分
.xls和.xlsx,可调整Directory.GetFiles的搜索模式或正则表达式
内容的提问来源于stack exchange,提问作者babno
相关产品推荐
相关产品推荐

