[英]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.