1、上傳Excel文件服務端
/// <summary> /// 任務導入基礎數據 /// </summary> /// <param name="tempId">模板id</param> /// <param name="advertId">廣告公司id</param> /// <returns></returns> public ActionResult Task_Import(int tempId,Guid advertId) { var data = OperateContext.Current.Execute<List<Task_TempData>>(rm => { var acc = UserAccount.Instance().GetUserInfo(); var companyId = acc.CompanyId; HttpFileCollectionBase files = HttpContext.Request.Files; if (files != null && files.Count == 1) { HttpPostedFileBase file = files[0]; if (file != null && !String.IsNullOrWhiteSpace(file.FileName) && (file.FileName.EndsWith(".xlsx") || file.FileName.EndsWith(".xls"))) { rm.RetData = OperateContext.Current.BLLSession.ITask_StagePlanInfoBLL.Task_Import(file.InputStream, file.FileName, companyId,advertId, tempId); OperateContext.Current.BLLSession.ISys_AccountLogBLL.AddLog(acc.AccountId, acc.Name, LogTypeEnum.重要, "任務導入基礎數據"); } else { rm.RetCode = 1; rm.RetMsg = "上傳的文件格式錯誤"; } } else { rm.RetCode = 1; rm.RetMsg = "未選擇文件"; } }); return Json(data, JsonRequestBehavior.AllowGet); }
2、上傳Excel文件js
// 上傳文件 scope.uploadFile = function () { if (!scope.ModelInfo.advertId) { layer.msg("請選擇廣告公司"); return; } if (!scope.ModelInfo.tempId) { layer.msg("請選擇模板"); return; } //file類型的input var file = document.getElementById("fileUpload").files[0]; if (!file) { layer.msg("請選擇文件"); return; } var form = new FormData(); form.append('file', file); //添加其他參數 form.append('advertId', scope.ModelInfo.advertId); form.append('tempId', scope.ModelInfo.tempId); layer.msg("正在導入數據,請勿進行任何操作,完成後會自動顯示結果"); layer.load(); //請求 http({ method: 'POST', url: 'Task_Import', data: form, headers: { 'Content-Type': undefined }, transformRequest: angular.identity }).success(function (res) { layer.closeAll(); if (res.RetCode == 0) { var data = res.RetData; scope.TotalCount = data.TotalCount; scope.SuccessCount = data.SuccessCount; scope.FailCount = data.FailCount; scope.Result = data.Result; scope.isResult = true; } else { layer.msg(res.RetMsg); } }).error(function (data) { layer.msg("上傳文件失敗"); }) }
3、解析數據類XSSFWorkbookImportHelper
using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Linq; namespace ElevatorAdvertising.Common { /// <summary> /// excel文件解析 /// </summary> public class XSSFWorkbookImportHelper { private XSSFWorkbookImportHelper() { } /// <summary> /// /// </summary> /// <param name="stream">導入文件流</param> /// <param name="fileName">文件名用於判斷XSSFWorkbook還是HSSFWorkbook</param> /// <param name="headerNumber">表頭下標</param> /// <param name="isNoCloseStream">是否關閉流</param> public XSSFWorkbookImportHelper(System.IO.Stream stream, string fileName, int headerNumber = 0, bool isNoCloseStream = true) { Data = new List<XSSFWorkbookImportCellData>(); Errors = new List<XSSFWorkbookImportError>(); try { IWorkbook workbook; if (fileName.EndsWith(".xlsx")) { workbook = new XSSFWorkbook(stream); } else { workbook = new HSSFWorkbook(stream); } ISheet sheet = workbook.GetSheetAt(0); if (sheet == null) throw new GeneralException(11, "Excel無工作表"); // 表頭即下標第temp.HeaderNumber行(0開始)數據,每列的列名 IRow headerRow = sheet.GetRow(headerNumber); if (headerRow == null) throw new GeneralException(11, "表中無任何數據"); List<dynamic> headers = new List<dynamic>(); foreach (var item in headerRow) { headers.Add(CellToValue(item)); } //遍歷行,從0開始 for (int i = sheet.FirstRowNum; i < sheet.LastRowNum; i++) { try { IRow row = sheet.GetRow(i); if (row != null) { //遍歷列,row.FirstCellNum有時爲1的問題 for (int c = 0; c < row.LastCellNum; c++) { try { var cell = row.GetCell(c); if (cell != null) { Data.Add(new XSSFWorkbookImportCellData() { RowNumber = i, ColumnNumber = c, ColumnName = headers.Count > c - row.FirstCellNum ? headers[c - row.FirstCellNum] : "", Value = CellToValue(cell) }); } } catch (Exception ex) { Errors.Add(new XSSFWorkbookImportError { RowNumber = i, ColumnNumber = c, Message = ex.Message }); } } } } catch (Exception ex) { Errors.Add(new XSSFWorkbookImportError { RowNumber = i, ColumnNumber = null, Message = ex.Message }); } } } catch (GeneralException ge) { Errors.Add(new XSSFWorkbookImportError { Message = ge.Message }); throw ge; } finally { if (isNoCloseStream && stream != null) stream.Close(); } } /// <summary> /// 所有數據 /// </summary> public List<XSSFWorkbookImportCellData> Data { get; } /// <summary> /// 最大行數 /// </summary> public int MaxRow { get { return Data.Max(x => x.RowNumber); } } /// <summary> /// 最大列數 /// </summary> public int MaxColumn { get { return Data.Max(x => x.ColumnNumber); } } /// <summary> /// 獲取某行 /// </summary> /// <param name="row"></param> /// <returns></returns> public List<XSSFWorkbookImportCellData> GetRows(int row) { return Data.Where(x => x.RowNumber == row).ToList(); } /// <summary> /// 異常單元格位置信息 /// </summary> public List<XSSFWorkbookImportError> Errors { get; } /// <summary> /// 異常數量 /// </summary> public int ErrorCount { get { return Errors.Count; } } /// <summary> /// 所有異常信息 /// </summary> public string Message { get { string res = ""; foreach (var item in Errors) { res += "行:" + item.RowNumber + ",列:" + item.ColumnNumber + "\n" + item.Message + "\n\n"; } return res; } } /// <summary> /// 格式化數據 /// </summary> /// <param name="cell"></param> /// <returns></returns> private dynamic CellToValue(ICell cell) { if (cell != null) { try { if (string.IsNullOrWhiteSpace(cell.StringCellValue)) { return null; } } catch {} try { return cell.NumericCellValue;//數字 } catch { } try { return cell.DateCellValue;//日期 } catch { } try { return cell.BooleanCellValue;//布爾 } catch { } try { return cell.StringCellValue;//字符串 } catch { } try { return cell.ErrorCellValue;//Byet } catch { } } return null; } /// <summary> /// 格式化數據 /// </summary> /// <param name="cell"></param> /// <returns></returns> private string CellToString(ICell cell) { if (cell != null) { try { return cell.StringCellValue;//字符串 } catch { } try { return cell.NumericCellValue.ToString();//數字 } catch { } try { return cell.DateCellValue.ToString();//日期 } catch { } try { return cell.BooleanCellValue.ToString();//布爾 } catch { } try { return cell.ErrorCellValue.ToString();//Byet } catch { } } return null; } } /// <summary> /// import參數 /// </summary> public class XSSFWorkbookImportModel { /// <summary> /// 導入文件流 /// </summary> public System.IO.Stream ImportStream { get; set; } /// <summary> /// 文件名 /// </summary> public string FileName { get; set; } /// <summary> /// 表頭行數 /// </summary> public int HeaderNumber { get; set; } /// <summary> /// 是否不關閉流,默認0關閉 /// </summary> public int IsNoCloseStream { get; set; } } /// <summary> /// 單元格數據 /// </summary> public class XSSFWorkbookImportCellData { /// <summary> /// 行 /// </summary> public int RowNumber { get; set; } /// <summary> /// 列 /// </summary> public int ColumnNumber { get; set; } /// <summary> /// 列名//單元格值,類型可選:bool、string、IRichTextString、DateTime、double /// </summary> public dynamic ColumnName { get; set; } /// <summary> /// 單元格值,類型可選:bool、string、IRichTextString、DateTime、double /// </summary> public dynamic Value { get; set; } } public class XSSFWorkbookImportError { /// <summary> /// 行 /// </summary> public int? RowNumber { get; set; } /// <summary> /// 列 /// </summary> public int? ColumnNumber { get; set; } public string Message { get; set; } } }
4、解析數據匹配進數據庫
#region 任務導入 /// <summary> /// 導入任務 /// </summary> /// <param name="stream"></param> /// <param name="fileName"></param> /// <param name="companyId">安裝公司id</param> /// <param name="advertId">廣告公司id</param> /// <param name="tempId">excel模板id</param> /// <returns></returns> public List<Task_TempData> Task_Import(System.IO.Stream stream, string fileName,Guid companyId, Guid advertId, int tempId) { //excel解析模板對象 var temp = DBSession.ITask_TempDAL.GetFirstBy(x => x.CompanyId == companyId && x.TempState == 1 && x.TempId == tempId); if (temp == null) { throw new GeneralException(1, "模板錯誤,請選擇可用模板"); } //解析excel var excel = new XSSFWorkbookImportHelper(stream, fileName, temp.HeaderNumber); if (excel.ErrorCount > 0) { LogHelper.Instance.Error("導入任務基礎數據失敗," + excel.Message); throw new GeneralException(1, "導入數據錯誤"); } //讀取表頭之後的數據 List<Task_TempData> tasks = new List<Task_TempData>(); for (int i = temp.HeaderNumber+1; i < excel.MaxRow; i++) { if (excel.Data[i] != null) { //獲取一行數據 var nows = excel.GetRows(i); //根據列名生成數據對象 var nowTime = DateTime.Now; tasks.Add(new Task_TempData() { DataId=Guid.NewGuid(), CompanyId= companyId, AdvertCompanyId=advertId, DataState=0, CreateTime=nowTime, AgreementState = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.AgreementState)?.Value + "", AgreementCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.AgreementCount)?.Value+ "", AgreementNumber = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.AgreementNumber)?.Value+ "", AgreementDate = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.AgreementDate)?.Value+ "", AgreementStart = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.AgreementStart)?.Value+ "", AgreementEnd = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.AgreementEnd)?.Value+ "", City = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.City)?.Value+ "", RegionName = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.RegionName)?.Value+ "", BusinessDistrict = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.BusinessDistrict)?.Value+ "", Block = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.Block)?.Value+ "", BuildingName = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.BuildingName)?.Value+ "", BuildingAddress = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.BuildingAddress)?.Value+ "", InstallJobName = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.InstallJobName)?.Value+ "", BuildingType = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.BuildingType)?.Value+ "", TabooIndustry = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.TabooIndustry)?.Value+ "", Developer = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.Developer)?.Value+ "", BuildingLevel = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.BuildingLevel)?.Value+ "", StationedDate = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.StationedDate)?.Value+ "", FloorNumber = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.FloorNumber)?.Value+ "", TungCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.TungCount)?.Value+ "", HomeCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.HomeCount)?.Value+ "", UnitCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.UnitCount)?.Value+ "", Rental = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.Rental)?.Value+ "", Price = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.Price)?.Value+ "", AveragePrice = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.AveragePrice)?.Value+ "", Occupancy = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.Occupancy)?.Value+ "", PeopleCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.PeopleCount)?.Value+ "", GroundParkingCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.GroundParkingCount)?.Value+ "", UndergroundParkingCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.UndergroundParkingCount)?.Value+ "", ElevatorCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.ElevatorCount)?.Value+ "", LiquidCrystalCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.LiquidCrystalCount)?.Value+ "", ElevatorMediaCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.ElevatorMediaCount)?.Value+ "", LiquidCrystalMedia2Count = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.LiquidCrystalMedia2Count)?.Value+ "", LobbyCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.LobbyCount)?.Value+ "", WaitingPositionCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.WaitingPositionCount)?.Value+ "", OtherMediaCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.OtherMediaCount)?.Value+ "", BusinessMediaCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.BusinessMediaCount)?.Value+ "", AvailableBusinessMediaCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.AvailableBusinessMediaCount)?.Value+ "", NoAvailableBusinessMediaCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.NoAvailableBusinessMediaCount)?.Value+ "", AvailablePublicWelfareMediaCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.AvailablePublicWelfareMediaCount)?.Value+ "", NoAvailablePublicWelfareMediaCount = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.NoAvailablePublicWelfareMediaCount)?.Value+ "", PropertyCompany = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.PropertyCompany)?.Value+ "", AudiencDes = nows.FirstOrDefault(x => (x.ColumnName + "").Replace("\n","") == temp.AudiencDes)?.Value+ "", }); } } //批量加入數據庫 Task_ImportDataBase(tasks); return tasks; } /// <summary> /// 任務基礎數據批量加入數據庫 /// </summary> private void Task_ImportDataBase(List<Task_TempData> tasks) { using (TransactionScope ts = new TransactionScope()) { try { foreach (var item in tasks) { DBSession.ITask_TempDataDAL.Add(item); } ts.Complete(); } catch (Exception ex) { ts.Dispose(); LogHelper.Instance.Error("保存任務基礎數據失敗," + ex.Message); throw new GeneralException(1, "保存任務基礎數據失敗"); } } } #endregion