使用EPPLUS c#读取,写入和回送修改后的xlxs文件

时间:2016-09-02 08:56:33

标签: c# excel epplus

我在将修改后的文件发送回客户端浏览器时遇到麻烦,如何使用NPOI将excell工作簿发送回客户端。 我的问题是将修改后的工作簿保存到内存流

这是我的代码:

public async Task<ActionResult> Upload(IEnumerable<HttpPostedFileBase> files)
{
    var errorFile = false;
    var result = new MemoryStream();
    if (files == null) return RedirectToAction("Index", "Employee");
    var file = files.SingleOrDefault(a => a != null);
    if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
    {
        var fileName = file.FileName;
        var fileContentType = file.ContentType;
        var fileBytes = new byte[file.ContentLength];
        var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));

        var defaultdate = new DateTime(1953, 1, 1);

        using (var package = new ExcelPackage(file.InputStream))
        {
            var currentSheet = package.Workbook?.Worksheets;
            if (currentSheet.Any())
            {
                var workSheet = currentSheet.First();
                var noOfRow = workSheet.Dimension.End.Row;

                using (var context = new PayrollContext())
                {
                    context.Configuration.AutoDetectChangesEnabled = false;
                    for (var rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
                    {
                        if (workSheet.Cells[$"A{rowIterator}"].Value == null) continue;
                        var employeeId = workSheet.Cells[$"A{rowIterator}"]?.Value?.ToString();
                        var lastName = workSheet.Cells[$"B{rowIterator}"]?.Value?.ToString();
                        var firstName = workSheet.Cells[$"C{rowIterator}"]?.Value?.ToString();
                        var middleName = workSheet.Cells[$"D{rowIterator}"]?.Value?.ToString();
                        var shiftCode = workSheet.Cells[$"E{rowIterator}"]?.Value?.ToString();
                        var _timeIn = workSheet.Cells[$"F{rowIterator}"]?.Value?.ToString();
                        var timeIn = !string.IsNullOrWhiteSpace(_timeIn) ? DateTime.Parse(_timeIn) : defaultdate;
                        var _timeOut = workSheet.Cells[$"J{rowIterator}"]?.Value?.ToString();
                        var timeOut = !string.IsNullOrWhiteSpace(_timeOut) ? DateTime.Parse(_timeOut) : defaultdate;
                        if (timeIn == defaultdate && timeOut == defaultdate && string.IsNullOrEmpty(shiftCode))
                        {
                            workSheet.Cells[$"J{rowIterator}"].Value = "This row requires either Timein-Time out date and time or provide the valid ShiftCode";
                            errorFile = true;
                        }
                        var employee = _employeeService.GetByName(firstName.Trim(), lastName.Trim());

                        if (shiftCode != null)
                        {
                            var shift = _shiftService.GetShift(shiftCode);
                            if (shift == null)
                            {
                                errorFile = true;
                                workSheet.Cells[$"J{rowIterator}"].Value = "Shift Code is not valid";
                            }
                            else
                            {
                                var schedule = new Schedules()
                                {
                                    EmployeeId = employee.EmployeeId,
                                    TimeOut = shift.TimeOut,
                                    TimeIn = shift.TimeOut,
                                    ShiftId = shift.Id,
                                    TotalHrs = Convert.ToInt32((timeOut - timeIn).TotalHours),
                                };
                                _employeeSchedService.Insert(schedule);
                            }
                        }
                        else
                        {
                            var schedule = new Schedules()
                            {
                                EmployeeId = employee.EmployeeId,
                                TimeOut = timeOut,
                                TimeIn = timeIn,
                                TotalHrs = Convert.ToInt32((timeOut - timeIn).TotalHours),
                            };
                            _employeeSchedService.Insert(schedule);
                        }
                    }

                    try
                    {
                        await _unitOfWorkAsync.SaveChangesAsync();
                        context.Configuration.AutoDetectChangesEnabled = false;
                    }
                    catch (DbEntityValidationException ex)
                    {
                        foreach (var failure in ex.EntityValidationErrors)
                        {
                            foreach (var error in failure.ValidationErrors)
                            {
                                ModelState.AddModelError(
                                    $"{failure.Entry.Entity.GetType()} failed validation\n",
                                    $"Error on {error.PropertyName} : {error.ErrorMessage}");
                            }
                        }
                    }
                }
                package.SaveAs(result);

            }
            else
            {
                ModelState.AddModelError("Invalid File", "Unable to read the Excel Worksheets!");
                return View("Index");
            }

        }

    }
    if (errorFile)
    {

        return File(result, file.ContentType, file.FileName);
    }
    return RedirectToAction("Index", "Employee");
}

0 个答案:

没有答案