using MiniExcelLibs; using System.IO; namespace ShrlAlgoToolkit.RevitAddins.Common.Extensions { public static class MiniExcelExtensions { // --- 写入部分 (Write) --- /// /// 开始流式配置 Excel 写入 /// public static Extensions.ExcelWriter AsExcel(this IEnumerable data) { return new Extensions.ExcelWriter(data); } /// /// 快速保存多 Sheet 字典到文件 /// public static void SaveAsExcel(this Dictionary sheetsData, string filePath, bool overwrite = true) { // 自动清理 Sheet 名称中的非法字符 var sanitizedData = new Dictionary(); foreach (var kvp in sheetsData) { sanitizedData.Add(SanitizeSheetName(kvp.Key), kvp.Value); } MiniExcel.SaveAs(filePath, sanitizedData, overwriteFile: overwrite); } // --- 读取部分 (Read) --- /// /// 从文件路径直接读取数据为强类型列表 /// public static IEnumerable ReadExcel(this string filePath, string sheetName = null) where T : class, new() { if (!File.Exists(filePath)) throw new FileNotFoundException("Excel文件不存在", filePath); return MiniExcel.Query(filePath, sheetName: sheetName); } /// /// 从文件路径读取为动态类型 (Dictionary/dynamic) /// public static IEnumerable ReadExcelDynamic(this string filePath, string sheetName = null) { if (!File.Exists(filePath)) throw new FileNotFoundException("Excel文件不存在", filePath); return MiniExcel.Query(filePath, sheetName: sheetName); } // --- 工具方法 --- /// /// 清理 Excel Sheet 名称中的非法字符 /// public static string SanitizeSheetName(string name) { if (string.IsNullOrEmpty(name)) return "Sheet1"; char[] invalidChars = { '\\', '/', '?', '*', '[', ']', ':' }; foreach (var c in invalidChars) name = name.Replace(c, '_'); return name.Length > 31 ? name.Substring(0, 31) : name; } } public class ExcelWriter { private readonly IEnumerable data; private string sheetName = "Sheet1"; private bool overwrite = true; public ExcelWriter(IEnumerable data) => this.data = data; /// /// 设置 Sheet 名称 /// public Extensions.ExcelWriter WithSheetName(string name) { sheetName = Extensions.MiniExcelExtensions.SanitizeSheetName(name); return this; } /// /// 设置是否覆盖 /// public Extensions.ExcelWriter Overwrite(bool canOverwrite = true) { overwrite = canOverwrite; return this; } /// /// 执行保存到文件 /// public void SaveTo(string filePath) { MiniExcel.SaveAs(filePath, data, sheetName: sheetName, overwriteFile: overwrite); } /// /// 转换为字节数组 (用于 Web 下载或内存操作) /// public byte[] ToBytes() { using (var ms = new MemoryStream()) { ms.SaveAs(data, sheetName: sheetName); return ms.ToArray(); } } } }