我知道如何写入单元格,但如何将 excel 文件中单元格内写入的现有字符串转换为字符串对象,以便我可以使用它在其他单元格中生成数据?
到目前为止我的代码:
Excel.ApplicationClass excelApp = new Excel.ApplicationClass();
excelApp.Visible = true;
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open("C:\\Users\\user\\Desktop\\list.xls", 0, false, 5, "", "",
false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "Sheet1";
Excel.Worksheet xlws = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
我可以使用类似的东西来操作单元格内容:
xlws.Cells[1,1] = "foo";
但我在做相反的事情时遇到了麻烦,即在我的程序中将单元格内容读入字符串。
如有任何帮助,我们将不胜感激。
最佳答案
为避免 NullReferenceException
,不要直接在可以为 null 的类型(object
、dynamic)上使用
、.ToString()
string
等)。以下是将对象转换为字符串的几种更安全的方法:
Convert.ToString(object)
- 返回String.Empty
当对象为空时object?.ToString()
- VS 2015 Null-conditional Operator如果对象为 null,则返回 nullobject?.ToString() ?? ""
- C# null-coalescing operator??
当对象为 null 时返回""
object + ""
- 当对象为 null 时,String.Concat 返回""
$"{object}"
- VS 2015 string interpolation是transformed at compile time调用等效的String.Format("{0}", object)
调用,并在对象为 null 时返回""
关于c# - 如何从 Excel 单元格中提取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5646145/