C# 如何通过行索引和列索引获取单元格的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2299516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the value of a cell by row index and column index
提问by CurlyFro
currently i'm doing this:
目前我正在这样做:
string cellValue = sheet.get_Range("A12", _missing).Value2.ToString();
this works but i really need to select a cell by row and column index.
这有效,但我真的需要按行和列索引选择一个单元格。
i get a null exception when i try
当我尝试时,我得到一个空异常
string cellValue = ((Range)sheet.Cells[row, column]).Value2.ToString();
any ideas?
有任何想法吗?
采纳答案by Zach Johnson
Where does the ArgumentNullException
occur? Try separating out your code like this and step through it:
ArgumentNullException
发生在哪里?尝试像这样分离您的代码并逐步执行它:
object rangeObject = sheet.Cells[row, column];
Range range = (Range)rangeObject;
object rangeValue = range.Value2;
string cellValue = rangeValue.ToString();
This will show you where the null object is.
这将显示空对象的位置。
回答by Joe Johnston
I had the same issue. The nullref would happen when the cell I was reading was empty.
我遇到过同样的问题。当我正在阅读的单元格为空时,会发生 nullref。
string foo = (((Range) ActiveWorksheet.Cells[row, column]).Value2 != null
? ((Range) ActiveWorksheet.Cells[row, column]).Value2.ToString()
: "Coalesce some false string here...");
Notice that you have to check for null beforeyou attempt to transform or cast the value.
请注意,您必须在尝试转换或转换值之前检查 null 。