嵌套的尝试/捕获块

时间:2019-01-15 17:03:32

标签: c# asp.net-mvc

我允许用户将数据从Excel文件上传到我的数据库,并且如果他们的单元格之一格式错误,则希望显示友好的错误消息。总共将有20个左右的单元要上传,但是现在我只尝试两个。我正在尝试的Excel上载在MedicalTotal字段中有一些随机文本,而应将其格式化为小数。我验证了我的代码正在寻找正确的领域。以下控制器代码不执行任何操作。没有任何内容写入数据库,并且重新加载了相同的视图。

在监视窗口中,我收到一条消息“ Convert.ToDecimal(table [0])抛出了System.FormatException类型的异常”,我已经尝试了同时使用Exception和FormatException的代码。我愿意接受其他捕获错误的方法,请记住,我将重复try / catch过程约20次。

[Authorize]
[HttpPost]
public ActionResult CreateBenefitSummary(HttpPostedFileBase FileUpload, Guid ResponseId)
{
    BenefitsUploadViewModel model = new BenefitsUploadViewModel();

if (FileUpload != null)
{
    // tdata.ExecuteCommand("truncate table OtherCompanyAssets");  
    if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    {

        string filename = FileUpload.FileName;
        string targetpath = Server.MapPath("~/Doc/");
        FileUpload.SaveAs(targetpath + filename);
        string pathToExcelFile = targetpath + filename;
        var connectionString = "";
        if (filename.EndsWith(".xls"))
        {
            connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
        }
        else if (filename.EndsWith(".xlsx"))
        {
            connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
        }

        var excelFile = new ExcelQueryFactory(pathToExcelFile);

        var table = (from a in excelFile.WorksheetRangeNoHeader("B2", "B32", "Benefits Template") select a[0]).ToList();

        TempData["ResponseId"] = ResponseId;
        try
        {
            Benefits b = new Benefits();
            b.ResponseId = ResponseId;
            try
            {
                b.MedicalTotal = Convert.ToDecimal(table[0]);
            }
            catch (FormatException)
            {
                model.ErrorList.Add("Medical Total cell must use Number, Currency, or Accounting format.");
            }
            b.StdSicknessAccident = Convert.ToDecimal(table[1]);
            if (model.ErrorList.Count > 0) {
                return View(model);
            }
            db.benefits.Add(b);
            db.SaveChanges();
        }

        catch (SqlException ex)
        {
            ViewBag.Message = ex.Message;
        }
        catch (Exception ex)
        {
            ViewBag.Message = ex.Message;
        }

        //deleting excel file from folder  
        if ((System.IO.File.Exists(pathToExcelFile)))
        {
            System.IO.File.Delete(pathToExcelFile);
        }
        TempData["ResponseId"] = ResponseId;
        return RedirectToAction("CreateBenefitSummary", "Surveys");

    }

}
return View();

}

1 个答案:

答案 0 :(得分:2)

您的convert.ToDecimal可能应该改用Decimal.TryParse,然后在if语句后显示错误消息,查看结果是否已解析。使用try / catch进行流量控制通常被认为是不好的做法。

类似:

Decimal decVal;
if (Decimal.TryParse(table[0], out decVal))
{
     b.MedicalTotal = decVal;
}
else
{
     model.ErrorList.Add("Medical Total cell must use Number, Currency, or Accounting format.");
}