参考博客:ASP.NET MVC下使用文件上传
参考博客:NPOI使用手册
参考博客:ASP.Net MVC利用NPOI导入导出Excel
参考博客:C# NPOI 导入与导出Excel文档 兼容xlsx, xls
文件上传代码块
#region EXCEL上传 /// <summary> /// EXCEL上传 /// </summary> /// <param name="fileData"></param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Post)] public JsonResult ExcelUpload(HttpPostedFileBase fileData) { json.HttpResult result = new json.HttpResult(); if (fileData == null) { result.state = json.ResultType.error.ToString(); result.message = ""; return Json(new { result }, JsonRequestBehavior.AllowGet); } try { // 文件上传后的保存路径 string filePath = Request.ApplicationPath + "UpLoad/Excel/"; if (CreateFilePath(filePath)) { string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称 string fileExtension = Path.GetExtension(fileName); // 文件扩展名 string saveName = Guid.NewGuid().ToString("N") + fileExtension; // 保存文件名称 string excelPath = filePath + saveName; fileData.SaveAs(filePath + saveName); DataTable dt = GetExcelData(excelPath); bool re = bll.ProductManager.AddDataTable(dt); common.SysLog.InsertListLog(common.SysLog.PRODUCT_MODULE, common.SysLog.OPERATE_INSERT_LIST, dt.Rows.Count); result.state = json.ResultType.success.ToString(); result.message = json.ResultMessage.SUCCESS; } } catch (Exception ex) { result.state = json.ResultType.error.ToString(); result.message = ex.Message; } return Json(new { result }, JsonRequestBehavior.AllowGet); } #endregion
组建DataTable代码块
#region 获取Excel DataTable /// <summary> /// 获取Excel DataTable /// </summary> /// <param name="filePath"></param> /// <returns></returns> private DataTable GetExcelData(string filePath) { DataTable dt = new DataTable(); IWorkbook workbook; string fileExt = Path.GetExtension(filePath).ToLower(); using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式 if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { return null; } } ISheet sheet = workbook.GetSheetAt(0); IRow headerRow = sheet.GetRow(sheet.FirstRowNum);//第一行为标题行 /***************************************/return dt; } #endregion
时间: 2024-10-07 05:29:52