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

本文关键字:捕获异常 失败 文档 excel 上传 | 更新日期: 2023-09-27 18:04:53

也许有人能帮我解决以下问题。默认值。我的web应用程序中的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);
}

thanks in advance

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

首先,您需要逐行添加到DB中,而不是单个提交。现在只需移动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);
}