[英]Dealing with empty cells when importing Excel file using EPPlus
I want to import data from Excel to DataBase using EPPLUS. 我想使用EPPLUS将数据从Excel导入数据库。 From here I took code: https://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6
从这里我拿了代码: https : //www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6
The problem is that sometimes in excel are empty Cells. 问题在于,有时在excel中为空单元格。 And if cell is empty then I receive an error:
NullReferenceException
, and my application stops. 如果单元格为空,则会收到错误消息:
NullReferenceException
,并且我的应用程序停止。 I think good solution would be assign null
value to specific variable if there is no reference eg if(LAST_NAME returns NullReferenceException then LAST_NAME = null)
- but I don't know how to do this in code. 我认为如果没有引用,例如,
if(LAST_NAME returns NullReferenceException then LAST_NAME = null)
可以将null
值分配给特定变量,这是很好的解决方案-但我不知道如何在代码中执行此操作。
var newRecord = new DB_USER
{
ID = Int32.Parse(worksheet.Cells[idColumn + row].Value.ToString()),
FIRST_NAME = worksheet.Cells[firstNameColumn + row].Value.ToString(),
LAST_NAME = worksheet.Cells[lastNameColumn + row].Value.ToString() //If this value has NullReferenceException then assign null or ""
};
如果您使用的是最新的C#版本(6.0),则可以使用null传播运算符 :
LAST_NAME = worksheet?.Cells[lastNameColumn + row]?.Value?.ToString()
I thing its fine to assign a empty string ie string.Empty
for empty cells .And if you are fine you can put it this way : 我可以为空单元格分配一个空字符串,即
string.Empty
。如果可以,可以这样写:
var newRecord = new DB_USER
{
ID = Int32.Parse(worksheet.Cells[idColumn + row].Value.ToString()),
FIRST_NAME = worksheet.Cells[firstNameColumn + row].Value.ToString(),
LAST_NAME = worksheet.Cells[lastNameColumn + row].Value ?? string.Empty).ToString() //for a null value assign a empty string else the string value
};
A cleaner approach would be Extension method : 一种更清洁的方法是扩展方法:
public static string ToNullSafeString(this object obj)
{
return (obj ?? string.Empty).ToString();
}
and use it as : 并用作:
LAST_NAME = worksheet.Cells[lastNameColumn + row].Value.ToNullSafeString();
still if you wish to return a null
instead of string.Empty
then a slight modification to ToNullSafeString
extension method above will work. 仍然,如果您希望返回
null
而不是string.Empty
则可以对上面的ToNullSafeString
扩展方法进行一些修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.