上传excel文档失败时捕获异常

时间:2016-08-30 09:14:26

标签: c# .net exception

也许有人可以帮助我解决以下问题。我的webapplication中的default.aspx页面包含一个上传控件。用户可以从Excel文档上载记录。但如果它抛出异常,我想收到记录行号并在消息框中显示(见下文):

if (FileUpload.HasFile)
{

    string path = string.Concat(Server.MapPath("~/Excel/" + FileUpload.FileName));
    FileUpload.SaveAs(path);
    string constr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);

    ITransaction trans = Data.Instance.NHibernateSession.BeginTransaction();
    try
    {
        using (OleDbConnection conn = new OleDbConnection(constr))
        {
            conn.Open();
            OleDbCommand command = new OleDbCommand("Select * from [Sheet$]", conn);
            OleDbDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    Relation relation = new Relatie();

                    relation.name = reader[0].ToString();
                    relation.function = reader[1].ToString();
                   relation.Email = reader[2].ToString();


                }

            }

            trans.Commit();

        }
    }
    catch(Exception ex)
    {
        trans.Rollback();

        System.Windows.Forms.MessageBox.Show("Upload document failed: ROW NUMBER..????????:" + ex.Message);



    }
    File.Delete(path);
}

提前致谢

1 个答案:

答案 0 :(得分:0)

首先,您需要逐行添加到DB,而不是单个commit.Now只需移动try catch块,将行保存到DB

if (FileUpload.HasFile)
{

string path = string.Concat(Server.MapPath("~/Excel/" + FileUpload.FileName));
FileUpload.SaveAs(path);
string constr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);

ITransaction trans = Data.Instance.NHibernateSession.BeginTransaction();
    using (OleDbConnection conn = new OleDbConnection(constr))
    {
        conn.Open();
        OleDbCommand command = new OleDbCommand("Select * from [Sheet$]", conn);
        OleDbDataReader reader = command.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Relation relation = new Relatie();
                try
                {


                  relation.name = reader[0].ToString();
                  relation.function = reader[1].ToString();
                  relation.Email = reader[2].ToString();

                  // Save to DB
               }
               catch(SqlException ex)
               {
                  // Get the data from relation object
               }
            }
        }

        trans.Commit();
    }
     File.Delete(path);
}