猿问

嵌套的 Try/Catch 块

我允许用户将数据从 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();


白衣非少年
浏览 172回答 1
1回答

POPMUISE

您的 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.");}
随时随地看视频慕课网APP
我要回答