首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C# 導出 Excel 自動命名:掃描目標文件夾獲取當日最大流水號

     編輯:程式設計疑難解答

需求

導出 Excel 文件命名格式:`MMDD_序號` (如 `0218_01`),同一文件夾下同一天序號遞增。

核心算法

  1. 構造前綴:`DateTime.Now.ToString("MMdd") + "_"`。
  2. 遍歷目標文件夾所有文件,篩選以該前綴開頭的文件。
  3. 解析文件名下劃線後的數字部分,取最大值。
  4. 新序號 = 最大值 + 1,格式化為兩位數 (`D2`)。

完整代碼


public string GetNextExportFileName(string folderPath) {
    string prefix = DateTime.Now.ToString("MMdd") + "_"; // 如 "0218_"
    int maxSeq = 0;

    if (Directory.Exists(folderPath)) {
        string[] files = Directory.GetFiles(folderPath);
        foreach (string file in files) {
            string fileName = Path.GetFileNameWithoutExtension(file); // 不含擴展名
            if (fileName.StartsWith(prefix)) {
                string seqPart = fileName.Substring(prefix.Length); // 取 "_xx" 後部分
                if (int.TryParse(seqPart, out int seq)) {
                    maxSeq = Math.Max(maxSeq, seq);
                }
            }
        }
    }
    int nextSeq = maxSeq + 1;
    return $"{prefix}{nextSeq:D2}.xlsx"; // 如 "0218_03.xlsx"
}

進階優化

  • 性能:文件量極大時,`Directory.EnumerateFiles` 流式處理避免一次性載入數組。
  • 併發安全:多進程/多線程同時導出可能產生重複序號。解決:
    - 檔案創建時用 `FileMode.CreateNew` 獨佔創建,捕獲 `IOException` 重試下一序號。
    - 或引入文件鎖 (`FileLock`)、數據庫序列表、Redis 原子增量。
  • 跨日期重置:前綴包含日期,自然實現每日歸零,無需額外邏輯。

併發安全版本片段


public string CreateUniqueExportFile(string folderPath) {
    string prefix = DateTime.Now.ToString("MMdd") + "_";
    for (int seq = 1; seq <= 99; seq++) {
        string fileName = $"{prefix}{seq:D2}.xlsx";
        string fullPath = Path.Combine(folderPath, fileName);
        try {
            // 嘗試獨佔創建文件流,原子操作
            using (FileStream fs = new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) {
                return fullPath; // 成功返回路徑,調用者寫入數據
            }
        } catch (IOException) {
            // 文件已存在,嘗試下一序號
        }
    }
    throw new InvalidOperationException("當日導出序號已用盡 (99)");
}

總結

掃描文件夾解析序號簡單有效,併發場景必須採用**原子性文件創建** (`FileMode.CreateNew`) 保證唯一性,而非單純掃描+計算。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved