[英]Adding Values with int.parse
我正在遍历一些excel单元格以求和单元格的值,某些单元格为空,并且Input string was not in the correct format
传递它们时,我收到了Input string was not in the correct format
错误的错误。 这是我的代码:
int total = 0;
int rowstart = 4;
while (ws.Cells[rowstart, 1].Value.ToString() != "")
{
if (ws.Cells[rowstart, 1].Value.ToString() !=
ws.Cells[rowstart + 1, 1].Value.ToString())
{
ws.InsertRow(rowstart + 1, 1);
ws.Cells[rowstart + 1, 3].Value = total;
}
else
{
total = total + int.Parse(ws.Cells[rowstart, 3].Value.ToString());
// I'm adding the value of Column 3 to the variable total,
I get the error if the cell is empty
rowstart = rowstart + 1;
}
}
我以为这是因为您无法解析空字符串,所以如果单元格为空,我如何只添加0?
使用int.TryParse
:
int parsed;
int.TryParse(ws.Cells[rowstart, 3].Value.ToString(), out parsed)
total += parsed;
如果字符串不是数字,则parsed
为0。
使用int.TryParse
而不是int.Parse
int total = 0;
int rowstart = 4;
while (ws.Cells[rowstart, 1].Value.ToString() != "")
{
int val=0;
if (ws.Cells[rowstart, 1].Value.ToString() != ws.Cells[rowstart + 1, 1].Value.ToString())
{
ws.InsertRow(rowstart + 1, 1);
ws.Cells[rowstart + 1, 3].Value = total;
}
else
{
int.TryParse(ws.Cells[rowstart, 3].Value.ToString(), out val);
total = total + val;
// I'm adding the value of Column 3 to the variable total, I get the error if the cell is empty
rowstart = rowstart + 1;
}
}
试试下面的代码
else
{
If (int.TryParse(ws.Cells[rowstart, 3].Value.ToString(), out result))
total = total +int.Parse(ws.Cells[rowstart, 3].Value.ToString());
rowstart = rowstart + 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.