使用Excel interlop c#.net查看单元格中的注释是否为空
嘿,我正在使用下面的代码,以便找出如果我parsing通过Excel表单中的单元格是否有注释。
int columnCount = ws.UsedRange.Columns.Count; Dictionary<string,bool> storedValidaters = new Dictionary<string, bool>(); for (int c = 1; c < columnCount; c++) { if (ws.Cells[2, c].Comment.Shape.AlternativeText != null) { string columnName = ws.Cells[2, c].Value2.ToString(); string myComment = ws.Cells[2, c].Comment.Shape.AlternativeText.ToString().Replace("Text Box: ", ""); storedValidaters.Add(columnName, true); } else { //the value is null so its false string columnName = ws.Cells[2, c].Value2.ToString(); storedValidaters.Add(columnName, false); } }
它循环几次,但一旦它到达一个没有评论的单元格,它就会呕吐。
出现无法对空引用执行运行时绑定的错误。
我做了一些search,看看是否有其他人有工作代码,以检查为空,但一直无法find一个工作的例子。
任何人都知道的方法来做到这一点?
我会build议改变:
Comment.Shape.AlternativeText
至:
Comment?.Shape?.AlternativeText
空条件运算符将确保代码将继续按预期方式工作,而不pipeComment
是否为null,或者Shape
为null或者AlternativeText
为null。