using System; using System.Collections.Generic; using System.IO; using unvell.ReoGrid; namespace WpfApp.Utils { /// /// Excel 操作静态工具类(基于 ReoGrid) /// public static class ExcelHelper { private static ReoGridControl reoGridControl; private static Worksheet currentSheet; static ExcelHelper() { reoGridControl = new ReoGridControl(); } /// /// 从模板加载 Excel 文件 /// public static void LoadTemplate(string filePath) { if (!File.Exists(filePath)) throw new FileNotFoundException($"模板文件不存在: {filePath}"); reoGridControl.Load(filePath); currentSheet = reoGridControl.CurrentWorksheet; } /// /// 切换到指定工作表 /// public static void SelectSheet(string sheetName) { if (reoGridControl == null) throw new InvalidOperationException("请先调用 LoadTemplate 方法加载文件。"); var sheet = reoGridControl.Worksheets[sheetName]; if (sheet == null) throw new ArgumentException($"未找到名为 '{sheetName}' 的工作表。"); currentSheet = sheet; reoGridControl.CurrentWorksheet = sheet; } /// /// 获取当前工作表名称 /// public static string GetCurrentSheetName() { return currentSheet?.Name ?? string.Empty; } /// /// 读取单元格 /// public static object ReadCell(string cellName) { return currentSheet?.GetCellData(cellName); } /// /// 设置单元格值 /// public static void WriteCell(string cellName, object value) { currentSheet?.SetCellData(cellName, value); } /// /// 批量写入单元格 /// public static void WriteCells(Dictionary cellValues) { foreach (var kv in cellValues) { currentSheet?.SetCellData(kv.Key, kv.Value); } } /// /// 在指定行插入数据(从 startColumn 开始) /// public static void InsertRowData(int rowIndex, int startColumn, IList values) { if (currentSheet == null) throw new InvalidOperationException("请先加载模板并选择工作表。"); for (int i = 0; i < values.Count; i++) { currentSheet[rowIndex, startColumn + i] = values[i]; } } /// /// 保存为新文件 /// public static void SaveAs(string savePath) { if (reoGridControl == null) throw new InvalidOperationException("请先调用 LoadTemplate 方法加载文件。"); reoGridControl.Save(savePath, unvell.ReoGrid.IO.FileFormat.Excel2007); } /// /// 打开 Excel 文件(并显示到 ReoGrid 控件) /// /// Excel 文件路径 /// 用于显示的 ReoGridControl 容器 public static void OpenExcel(string filePath, ReoGridControl reoGridHost) { if (!File.Exists(filePath)) throw new FileNotFoundException($"文件不存在: {filePath}"); // 替换当前控件引用 reoGridControl?.Dispose(); reoGridControl = reoGridHost; // 加载 Excel 文件 reoGridControl.Load(filePath); // 默认显示第一个工作表 currentSheet = reoGridControl.CurrentWorksheet; } /// /// 清理资源 /// public static void Dispose() { reoGridControl?.Dispose(); reoGridControl = null; currentSheet = null; } } }