0

我正在读取一个 excel 文件,每当我读取一个具有错误值的字段时,都会停止执行并转到 catch 部分。(例如在 dateTime 列中有一个字符串)我希望能够在不停止执行的情况下完成循环并将我遇到的所有错误消息存储在 stringbuilder 对象中。我不希望用户在遇到错误时更正输入文件。字符串生成器对象应显示文件中的所有错误。

请问我怎样才能做到这一点?我试过继续没有运气。

public void  testThis()
{
    try
    {
        for (int rowNumber = startRow + 1; rowNumber <= currentWorkSheet.Dimension.End.Row; rowNumber++)
        // read each row from the start of the data (start row + 1 header row) to the end of the spreadsheet.
        {
            object col1Value = currentWorkSheet.Cells[rowNumber, 1].Value;
            object col2Value = currentWorkSheet.Cells[rowNumber, 2].Value;
            object col3Value = currentWorkSheet.Cells[rowNumber, 3].Value;
            object col4Value = currentWorkSheet.Cells[rowNumber, 4].Value;

            if ((col1Value != null && col2Value != null))
            {
                exampleDataList.Add(new PersonalData
                {
                    firstname = col1Value.ToString(),
                    lastname = col2Value.ToString(),
                    currentDate = col3Value == null ? DateTime.MinValue : Convert.ToDateTime(col3Value),
                    mySalary = col4Value == null ? 0 : Convert.ToInt32(col4Value)
                });
            }

        }
    }
    catch(Exception Exception)
    {
        //continue.. do not stop
    }

}
4

2 回答 2

2

将你的Try..Catch块移动到For循环中

StringBuilder sb = new StringBuilder();
for (int rowNumber = startRow + 1; rowNumber <= currentWorkSheet.Dimension.End.Row; rowNumber++)
        // read each row from the start of the data (start row + 1 header row) to the end of the spreadsheet.
{

    try
    {

        object col1Value = currentWorkSheet.Cells[rowNumber, 1].Value;
        object col2Value = currentWorkSheet.Cells[rowNumber, 2].Value;
        object col3Value = currentWorkSheet.Cells[rowNumber, 3].Value;
        object col4Value = currentWorkSheet.Cells[rowNumber, 4].Value;

        if ((col1Value != null && col2Value != null))
        {
            exampleDataList.Add(new PersonalData
            {
                firstname = col1Value.ToString(),
                lastname = col2Value.ToString(),
                currentDate = col3Value == null ? DateTime.MinValue : Convert.ToDateTime(col3Value),
                mySalary = col4Value == null ? 0 : Convert.ToInt32(col4Value)
            });
        }

    }      
    catch (Exception e)
    {
         //log exception here
        sb.AppendFormat("{0}: {1}{2}",rowNumber, e.Message, Environment.NewLine);           
    }
} 

//convert the StringBuilder into the final string object
string allMessages = sb.ToString();
于 2013-07-08T22:04:38.217 回答
0

问题是您必须将 try/catch 放在 for 内部,而不是外部!

那么在catch中你可以使用或者不使用continue,无所谓!

在进入 for 循环之前创建StringBuilderistance,在 for 之后,您可以使用 a 显示其内容.ToString()

于 2013-07-08T22:05:02.577 回答