[英]Adding Values with int.parse
I'm looping through some excel cells to sum the values of the cells, some of the cells are empty and i'm getting a Input string was not in the correct format
error when I pass them. 我正在遍历一些excel单元格以求和单元格的值,某些单元格为空,并且
Input string was not in the correct format
传递它们时,我收到了Input string was not in the correct format
错误的错误。 Here's my code: 这是我的代码:
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;
}
}
I was thinking it's because you can't parse an empty string, so how do I just add 0 if the cell is empty? 我以为这是因为您无法解析空字符串,所以如果单元格为空,我如何只添加0?
Use int.TryParse
: 使用
int.TryParse
:
int parsed;
int.TryParse(ws.Cells[rowstart, 3].Value.ToString(), out parsed)
total += parsed;
parsed
will be 0 if the string wasn't a number. 如果字符串不是数字,则
parsed
为0。
Use int.TryParse
instead of int.Parse
使用
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;
}
}
Try the code below 试试下面的代码
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.