SpreadsheetGear.Windows.Wpf使用无效工作簿名引用时崩溃求助
问题分析与解决方案
问题描述
在SpreadsheetGear中,当使用包含无效工作表名称的公式(例如=Death!A1,其中Death工作表不存在)时:
- WinForms版本会正常弹出「无效公式」提示
- WPF版本直接崩溃,抛出
XamlParseException,内部异常为ArgumentException: '꒾' is not a valid value for property 'Name',崩溃点在SpreadsheetGear内置MessageDialog的InitializeComponent方法加载XAML资源时。
临时解决方案
1. 提前验证公式有效性
在用户输入公式后、提交到单元格前,手动检查公式引用的工作表是否存在,避免触发控件内部bug:
// 假设ws是当前IWorksheet实例,formula是用户输入的公式 var workbook = ws.Workbook; // 提取公式中的工作表名称(简单示例,复杂公式建议用SpreadsheetGear专业解析API) var sheetName = ExtractSheetNameFromFormula(formula); if (!string.IsNullOrEmpty(sheetName) && workbook.Worksheets[sheetName] == null) { MessageBox.Show("引用的工作表不存在,请检查公式"); return; } // 验证通过后再设置单元格公式 ws.Cells["A1"].Formula = formula;
更可靠的方式是使用SpreadsheetGear的公式解析器获取所有引用:
var parser = ws.WorkbookSet.FormulaParser; var parseResult = parser.Parse(formula, ws.Cells["A1"]); foreach (var reference in parseResult.References) { if (reference is IInternalReference internalRef && internalRef.Worksheet == null) { MessageBox.Show($"引用的工作表「{internalRef.WorksheetName}」不存在"); return; } }
2. 全局捕获未处理异常
在WPF应用的App.xaml.cs中添加全局异常处理,避免程序直接崩溃:
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); DispatcherUnhandledException += App_DispatcherUnhandledException; } private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { if (e.Exception.InnerException is ArgumentException argEx && argEx.Message.Contains("is not a valid value for property 'Name'")) { MessageBox.Show("公式引用无效,请检查输入的工作表名称"); e.Handled = true; // 标记异常已处理,阻止程序崩溃 } }
根本解决途径
该问题属于SpreadsheetGear WPF控件的内部bug:其内置消息对话框的XAML资源中使用了不符合WPF命名规范的字符(如꒾)作为控件Name属性值,导致加载时抛出异常。需向SpreadsheetGear官方提交bug报告,请求修复该XAML资源的命名问题。
内容的提问来源于stack exchange,提问作者Jason Adam
相关产品推荐
相关产品推荐

