我允許用戶將數(shù)據(jù)從 Excel 文件上傳到我的數(shù)據(jù)庫,如果其中一個(gè)單元格的格式錯(cuò)誤,我希望顯示友好的錯(cuò)誤消息。總共將要上傳 20 個(gè)左右的單元格,但現(xiàn)在我只嘗試兩個(gè)。我正在嘗試的 Excel 上傳在 MedicalTotal 字段中有一些隨機(jī)文本,而應(yīng)將其格式化為小數(shù)。我確認(rèn)我的代碼正在查看正確的字段。以下控制器代碼什么都不做。沒有任何內(nèi)容寫入數(shù)據(jù)庫,并且重新加載相同的視圖。在監(jiān)視窗口中,我收到一條消息“Convert.ToDecimal(table[0]) 引發(fā)了 System.FormatException 類型的異?!蔽乙呀?jīng)嘗試了帶有 Exception 和 FormatException 的代碼。我對(duì)其他捕獲錯(cuò)誤的方法持開放態(tài)度,請(qǐng)記住,我將重復(fù) 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();
1 回答

POPMUISE
TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
您的 convert.ToDecimal 應(yīng)該使用 Decimal.TryParse 代替,然后在 if 語句后顯示錯(cuò)誤消息,查看結(jié)果是否已解析。使用 try/catch 進(jìn)行流量控制通常被認(rèn)為是不好的做法。
就像是:
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.");
}
- 1 回答
- 0 關(guān)注
- 144 瀏覽
添加回答
舉報(bào)
0/150
提交
取消