导入数据xlsx
#region 导入数据 /// <summary> /// 导入数据 /// </summary> /// <returns></returns> [HttpPost] public async Task<IActionResult> SubmitImportDate() { try { var files = Request.Form.Files; //没有文件上传,直接返回 if (files[0].Length == 0 || string.IsNullOrEmpty(files[0].FileName)) { return await Task.Run(() => ResultWarning($"{FrameworkMessage.MSG0000} :没有文件上传")).ConfigureAwait(false); } var file = files[0]; //没有文件上传,直接返回 if (file == null || string.IsNullOrEmpty(file.FileName) || file.Length == 0) { return await Task.Run(() => ResultWarning($"{FrameworkMessage.MSG0000} :没有文件上传")).ConfigureAwait(false); } string FileEextension = Path.GetExtension(files[0].FileName); if (FileEextension != ".xls" && FileEextension != ".xlsx") { return await Task.Run(() => ResultWarning($"{FrameworkMessage.MSG0000} :只能上传Excel文档")).ConfigureAwait(false); } //获取一个streamfile对象,该对象指向一个上传文件,准备读取该文件的内容 Stream streamfile = file.OpenReadStream(); byte[] bytes = null; using (var binaryReader = new BinaryReader(file.OpenReadStream())) { bytes = binaryReader.ReadBytes((int)streamfile.Length); } MemoryStream stream = new MemoryStream(bytes); ISheet sheet; if (FileEextension == ".xlsx") { XSSFWorkbook workbook = new XSSFWorkbook(stream); sheet = workbook.GetSheetAt(0); } else { HSSFWorkbook workbook = new HSSFWorkbook(stream); sheet = workbook.GetSheetAt(0); } #region 模板简单验证 //验证模板列数 if (sheet.GetRow(0) == null || sheet.GetRow(0).Cells.Count != 6) { return await Task.Run(() => ResultWarning($"{FrameworkMessage.MSG0000} :导入的模板错误")).ConfigureAwait(false); } //验证列名 if (GetCellString(sheet, "0", false, 0, 0) != "11*" || GetCellString(sheet, "0", false, 0, 1) != "22*" || GetCellString(sheet, "0", false, 0, 2) != "33*" || GetCellString(sheet, "0", false, 0, 3) != "444*" || GetCellString(sheet, "0", false, 0, 4) != "55*" || GetCellString(sheet, "0", false, 0, 5) != "备注" ) { return await Task.Run(() => ResultWarning($"{FrameworkMessage.MSG0000} :导入的模板错误")).ConfigureAwait(false); } #endregion #region 数据处理 #endregion return await Task.Run(() => ResultWarning("导入数据成功")).ConfigureAwait(false); } catch (Exception ex) { return await Task.Run(() => ResultWarning($"{FrameworkMessage.MSG0000} :导入预览数据异常,{ex.Message}")).ConfigureAwait(false); } } #endregion