Example #1
0
 public void Dispose()
 {
     if (_wb != null)
     {
         _wb.Dispose();
     }
     _wb = null;
 }
Example #2
0
        public void ExportExcel(DataSet ds, string destination)
        {
            var workbook = new ClosedXML.Excel.XLWorkbook();

            foreach (DataTable dt in ds.Tables)
            {
                var worksheet = workbook.Worksheets.Add(dt.TableName);
                worksheet.Cell(1, 1).InsertTable(dt);
                worksheet.Columns().AdjustToContents();
            }
            workbook.SaveAs(destination);
            workbook.Dispose();
        }
        static void Main(string[] args)
        {
            //Console.WriteLine("Hello World!");

            var s     = GetExcelPath();
            var bytes = GetExcel(s);
            var wb    = new ClosedXML.Excel.XLWorkbook(new MemoryStream(bytes));

            IEnumerable <SimpleTable> data = wb.ReadTable <SimpleTable>(1);


            var l = wb.ReadTable <Models.TableWithHeaders>(1,
                                                           new ReadOptions()
            {
                TitlesInFirstRow = true
            });

            Console.WriteLine(l.ToList().Count);


            //Example with trasnformations
            Expression <Func <string, DateTime> > fConvertData  = _ => DateTime.Now.AddDays(10);
            Expression <Func <string, bool> >     fSelectToBool = c => c == "x";

            var ls = wb.ReadTable <Models.TableWithHeadersAndBoleanConversion>(1,
                                                                               new ReadOptions()
            {
                TitlesInFirstRow = true,
                Converters       = new Dictionary <string, LambdaExpression>()
                {
                    { nameof(TableWithHeadersAndBoleanConversion.Birthday), fConvertData },
                    { nameof(TableWithHeadersAndBoleanConversion.Selected), fSelectToBool },
                }
            });

            wb.Dispose();



            Console.WriteLine(ls.ToList().Count);

            Console.ReadLine();
        }
        public static IList <CruiseData> getCruisedataFromExcel()
        {
            IList <CruiseData> cruisedataList = new List <CruiseData>();

            XLS.XLWorkbook workbook  = new XLS.XLWorkbook(@"C:\Users\fleet\Documents\cruises.xlsx");
            var            worksheet = workbook.Worksheet(1);
            var            usedRange = worksheet.RangeUsed();

            for (int i = 1; i <= usedRange.RowCount(); i++)
            {
                CruiseData cs = new CruiseData();
                cs.cruise = worksheet.Row(i).Cell(1).GetValue <String>();
                cs.ship   = worksheet.Row(i).Cell(2).GetValue <String>();
                cs.price  = worksheet.Row(i).Cell(3).GetValue <String>();
                cruisedataList.Add(cs);
            }
            workbook.Dispose();
            return(cruisedataList);
        }
        //Excel
        //получение excel файла, содержащем только расчет по заявке
        public ActionResult GetSpecificationFileOnlyCalculation(int claimId, int cv)
        {
            XLWorkbook excBook = null;
            var ms = new MemoryStream();
            var error = false;
            var message = string.Empty;
            try
            {

                //получение позиций по заявке и расчетов к ним
                var db = new DbEngine();
                var positions = db.LoadSpecificationPositionsForTenderClaim(claimId, cv);
                var facts = db.LoadProtectFacts();
                if (positions.Any())
                {
                    var calculations = db.LoadCalculateSpecificationPositionsForTenderClaim(claimId, cv);
                    if (calculations != null && calculations.Any())
                    {
                        foreach (var position in positions)
                        {
                            if (position.State == 1) continue;
                            position.Calculations =
                                calculations.Where(x => x.IdSpecificationPosition == position.Id).ToList();
                        }
                    }
                    var filePath = Path.Combine(Server.MapPath("~"), "App_Data", "Specification_fin.xlsx");
                    using (var fs = System.IO.File.OpenRead(filePath))
                    {
                        var buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Count());
                        ms.Write(buffer, 0, buffer.Count());
                        ms.Seek(0, SeekOrigin.Begin);
                    }
                    //создание файла excel с инфой по расчетам
                    excBook = new XLWorkbook(ms);
                    var workSheet = excBook.Worksheet("WorkSheet");
                    workSheet.Name = "лот";
                    var claim = db.LoadTenderClaimById(claimId);
                    //>>>>>>>>Шапка - Заполнение инфы о заявке<<<<<<

                    //Менеджер из Москвы
                    bool managerIsMoscou = false;
                    string managerSid = GetUser().Id;
                    var dtUserIsMoscou = Db.CheckManagerIsMoscou(managerSid);
                    if (dtUserIsMoscou.Rows.Count > 0)
                    {
                        managerIsMoscou = dtUserIsMoscou.Rows[0]["result"].ToString().Equals("1");
                    }
                    // />Менеджер из Москвы

                    var dealTypes = db.LoadDealTypes();
                    var deliveryTimes = db.LoadDeliveryTimes();
                    UserBase manager;
                    try
                    {
                        manager = UserHelper.GetUserById(claim.Manager.Id);
                    }
                    catch (Exception ex)
                    {
                        manager = new UserBase();
                    }
                    var dt = Db.GetExchangeRatesOnDate(DateTime.Now);

                    double? usdRate = null;
                    double? eurRate = null;

                    if (dt.Rows.Count >= 3)
                    {
                        usdRate = Convert.ToDouble(dt.Rows[1]["price"].ToString()) * 1.03;
                        eurRate = Convert.ToDouble(dt.Rows[2]["price"].ToString()) * 1.03;
                    }

                    int rowHead = 1;

                    var usdCell = workSheet.Cell(rowHead, 4);
                    usdCell.Value =
                        usdRate.HasValue
                            ? usdRate.Value.ToString("N2")
                            : string.Empty;
                    workSheet.Cell(rowHead, 4).DataType = XLCellValues.Number;

                    var eurCell = workSheet.Cell(++rowHead, 4);
                    eurCell.Value = eurRate.HasValue
                            ? eurRate.Value.ToString("N2")
                            : string.Empty;
                    workSheet.Cell(rowHead, 4).DataType = XLCellValues.Number;

                    var eurRicohCell = workSheet.Cell(++rowHead, 4);
                    var profitCell = workSheet.Cell(++rowHead, 4);//Рентабельность
                    workSheet.Cell(++rowHead, 4).Value = dealTypes.First(x => x.Id == claim.DealType).Value;
                    workSheet.Cell(++rowHead, 4).Value = manager != null ? manager.ShortName : string.Empty;
                    workSheet.Cell(++rowHead, 4).Value = claim.Customer;
                    //срок готовности цен от снабжения???
                    rowHead++;
                    workSheet.Cell(++rowHead, 4).Value = claim.Sum;//Максимальная цена контракта???
                    workSheet.Cell(++rowHead, 4).Value = claim.DeliveryDateString;
                    workSheet.Cell(rowHead, 4).DataType = XLCellValues.DateTime;
                    workSheet.Cell(++rowHead, 4).Value = claim.DeliveryPlace;
                    workSheet.Cell(++rowHead, 4).Value = claim.KPDeadlineString;
                    workSheet.Cell(rowHead, 4).DataType = XLCellValues.DateTime;
                    workSheet.Cell(++rowHead, 4).Value = claim.AuctionDateString;
                    workSheet.Cell(rowHead, 4).DataType = XLCellValues.DateTime;
                    workSheet.Cell(++rowHead, 4).Value = claim.Comment;

                    //workSheet.Cell(3, 4).Value = claim.TenderNumber;
                    //workSheet.Cell(4, 4).Value = claim.TenderStartString;
                    //workSheet.Cell(4, 4).DataType = XLCellValues.DateTime;
                    //workSheet.Cell(5, 4).Value = claim.ClaimDeadlineString;
                    //workSheet.Cell(5, 4).DataType = XLCellValues.DateTime;
                    //workSheet.Cell(8, 4).Value = claim.CustomerInn;
                    //workSheet.Cell(9, 4).Value = !claim.Sum.Equals(0) ? claim.Sum.ToString("N2") : string.Empty;
                    //workSheet.Cell(11, 4).Value = claim.TenderUrl;
                    //workSheet.Cell(13, 4).Value = claim.Manager.SubDivision;
                    //workSheet.Cell(14, 4).DataType = XLCellValues.DateTime;

                    //заголовок для расчетов
                    //workSheet.Cell(18, 1).Value = "№ пп";
                    //workSheet.Cell(18, 2).Value = "Каталожный номер*";
                    //workSheet.Cell(18, 3).Value = "Наименование*";
                    //workSheet.Cell(18, 4).Value = "Замена";
                    //workSheet.Cell(18, 5).Value = "Цена за ед.";
                    //workSheet.Cell(18, 6).Value = "Сумма вход";
                    //workSheet.Cell(18, 7).Value = "Валюта";
                    ////workSheet.Cell(13, 7).Value = "Цена за ед. руб";
                    ////workSheet.Cell(13, 8).Value = "Сумма вход руб*";
                    //workSheet.Cell(18, 8).Value = "Поставщик";
                    //workSheet.Cell(18, 9).Value = "Факт получ.защиты*";
                    //workSheet.Cell(18, 10).Value = "Условия защиты";
                    //workSheet.Cell(18, 11).Value = "Цена с ТЗР";
                    //workSheet.Cell(18, 12).Value = "Сумма с ТЗР";
                    //workSheet.Cell(18, 13).Value = "Цена с НДС";
                    //workSheet.Cell(18, 14).Value = "Сумма с НДС";
                    //workSheet.Cell(18, 15).Value = "Комментарий";
                    //var calcHeaderRange = workSheet.Range(workSheet.Cell(18, 1), workSheet.Cell(18, 15));
                    //calcHeaderRange.Style.Font.SetBold(true);
                    //calcHeaderRange.Style.Fill.BackgroundColor = XLColor.FromArgb(0, 204, 255, 209);
                    //calcHeaderRange.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                    //calcHeaderRange.Style.Border.SetBottomBorder(XLBorderStyleValues.Thin);
                    //calcHeaderRange.Style.Border.SetBottomBorderColor(XLColor.Gray);
                    //calcHeaderRange.Style.Border.SetTopBorder(XLBorderStyleValues.Thin);
                    //calcHeaderRange.Style.Border.SetTopBorderColor(XLColor.Gray);
                    //calcHeaderRange.Style.Border.SetRightBorder(XLBorderStyleValues.Thin);
                    //calcHeaderRange.Style.Border.SetRightBorderColor(XLColor.Gray);
                    //calcHeaderRange.Style.Border.SetLeftBorder(XLBorderStyleValues.Thin);
                    //calcHeaderRange.Style.Border.SetLeftBorderColor(XLColor.Gray);
                    //var currencies = db.LoadCurrencies();
                    //<<<<<<<Номер строки - начало вывода инфы>>>>>>
                    var row = rowHead+2;
                    int firstRow = row;
                    var rowNumber = 1;
                    //строки расчета
                    foreach (var position in positions)
                    {
                        position.Name = position.Name.Replace("\n", "").Replace("\r", "");

                        if (position.Calculations != null && position.Calculations.Any())
                        {
                            foreach (var calculation in position.Calculations)
                            {
                                calculation.Name = calculation.Name.Replace("\n", "").Replace("\r", "");

                                int col = 0;
                                workSheet.Cell(row, ++col).Value = rowNumber;
                                workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);

                                workSheet.Cell(row, ++col).Value = position.CatalogNumber;
                                    //? position.CatalogNumber
                                    //: calculation.CatalogNumber;
                                double hPosCatNum = GetCellHeight(workSheet.Cell(row, col).Value.ToString().Length, 30);
                                workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);

                                workSheet.Cell(row, ++col).Value = position.Name;
                                double hPosName = GetCellHeight(workSheet.Cell(row, col).Value.ToString().Length, 40);
                                    //String.IsNullOrEmpty(calculation.Name)? position.Name: calculation.Name;
                                workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Left);

                                workSheet.Cell(row, ++col).Value = calculation.CatalogNumber;
                                double hCalcCatNum = GetCellHeight(workSheet.Cell(row, col).Value.ToString().Length, 30);
                                workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);

                                workSheet.Cell(row, ++col).Value = calculation.Name + (!String.IsNullOrEmpty(calculation.Name) ? "\r\n" : "")+  (!String.IsNullOrEmpty(calculation.Replace) ? "Замена:\r\n" + calculation.Replace : String.Empty);
                                double hCalcName = GetCellHeight(workSheet.Cell(row, col).Value.ToString().Length, 40);
                                workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Left);
                                //workSheet.Cell(row, ++col).Value = calculation.Replace;
                                //workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Left);

                                workSheet.Cell(row, ++col).Value = GetUnitStr(position.Unit);
                                workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                                var countCell = workSheet.Cell(row, ++col);
                                countCell.Value = position.Value;

                                countCell.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                                if (position.ProductManager != null)
                                {
                                    var prodManager = UserHelper.GetUserById(position.ProductManager.Id);
                                    workSheet.Cell(row, ++col).Value = prodManager == null
                                        ? String.Empty
                                        : prodManager.ShortName;
                                }
                                double hProdManager = GetCellHeight(workSheet.Cell(row, col).Value.ToString().Length, 16);
                                workSheet.Cell(row, ++col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                                if (calculation.DeliveryTime != null)
                                {
                                    var delivTime = deliveryTimes.First(x => x.Id == calculation.DeliveryTime.Id);
                                    workSheet.Cell(row, col).Value = delivTime == null ? String.Empty : delivTime.Value;
                                }
                                double hCalcDeliv = GetCellHeight(workSheet.Cell(row, col).Value.ToString().Length, 16);
                                workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                                string partNum4Online = String.IsNullOrEmpty(position.CatalogNumber)? calculation.CatalogNumber: position.CatalogNumber;
                                    string onlinePrice = String.Empty;
                                try
                                {onlinePrice = CatalogProduct.PriceRequest(partNum4Online);}
                                catch {

                                }
                                workSheet.Cell(row, ++col).Value = onlinePrice;//Цена B2B
                                workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);

                                var priceUsdCell = workSheet.Cell(row, ++col);
                                priceUsdCell.Value = calculation.PriceUsd;
                                priceUsdCell.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right);
                                priceUsdCell.Style.NumberFormat.Format = "$ #,##0.00";
                                var priceEurCell = workSheet.Cell(row, ++col);
                                priceEurCell.Value = calculation.PriceEur;
                                priceEurCell.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right);
                                priceEurCell.Style.NumberFormat.Format = "€ #,##0.00";
                                var priceEurRicohCell = workSheet.Cell(row, ++col);
                                priceEurRicohCell.Value = calculation.PriceEurRicoh;
                                priceEurRicohCell.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right);
                                priceEurRicohCell.Style.NumberFormat.Format = "€ #,##0.00";
                                var priceRublCell = workSheet.Cell(row, ++col);
                                priceRublCell.Value = calculation.PriceRubl;
                                priceRublCell.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right);

                                //Вход за ед
                                if (String.IsNullOrEmpty(priceRublCell.Value.ToString().Trim()))
                                {
                                    if (!String.IsNullOrEmpty(priceEurRicohCell.Value.ToString().Trim()))
                                    {
                                        priceRublCell.FormulaR1C1 = String.Format("{0}*{1}", eurRicohCell.Address.ToStringFixed(), priceEurRicohCell.Address);
                                    }
                                    if (!String.IsNullOrEmpty(priceEurCell.Value.ToString().Trim()))
                                    {
                                        priceRublCell.FormulaR1C1 = String.Format("{0}*{1}", eurCell.Address.ToStringFixed(), priceEurCell.Address);
                                    }
                                    if (!String.IsNullOrEmpty(priceUsdCell.Value.ToString().Trim()))
                                    {
                                        priceRublCell.FormulaR1C1 = String.Format("{0}*{1}", usdCell.Address.ToStringFixed(), priceUsdCell.Address);
                                    }

                                }
                                // />Вход за ед
                                priceRublCell.Style.NumberFormat.Format = "₽ #,##0.00";
                                //Сумма
                                var priceSumCell = workSheet.Cell(row, ++col);
                                priceSumCell.Style.NumberFormat.Format = "₽ #,##0.00";
                                priceSumCell.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right);
                                priceSumCell.FormulaR1C1 = String.Format("{0}*{1}", countCell.Address,
                                    priceRublCell.Address);
                                // />Сумма

                                //Цена с ТЗР
                                var priceTzrCell = workSheet.Cell(row, ++col);
                                string formulaPriceTzrCell = String.Format("(({0}*1.02)*1.02)", priceRublCell.Address);
                                if (managerIsMoscou)
                                {
                                    formulaPriceTzrCell = String.Format("({0}*1.02)", priceRublCell.Address);
                                }
                                priceTzrCell.FormulaR1C1 = formulaPriceTzrCell;
                                priceTzrCell.Style.NumberFormat.Format = "₽ #,##0.00";
                                priceTzrCell.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right);
                                // /> Цена с ТЗР

                                //Сумма с ТЗР
                                var sumTzrCell = workSheet.Cell(row, ++col);
                                string formulaSumTzrCell = String.Format("{0}*{1}", countCell.Address,priceTzrCell.Address);
                                sumTzrCell.FormulaR1C1 = formulaSumTzrCell;
                                sumTzrCell.Style.NumberFormat.Format = "₽ #,##0.00";
                                sumTzrCell.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right);
                                // /> Сумма с ТЗР

                                //Цена С НДС
                                var priceNdsCell = workSheet.Cell(row, ++col);
                                string formulaPriceNdsCell = String.Format("{0}*(1+({1}/100))", priceTzrCell.Address, profitCell.Address);
                                priceNdsCell.FormulaR1C1 = formulaPriceNdsCell;
                                priceNdsCell.Style.NumberFormat.Format = "₽ #,##0.00";
                                priceNdsCell.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right);
                                // /> Цена с НДС

                                //Сумма с НДС
                                var sumNdsCell = workSheet.Cell(row, ++col);
                                string formulaSumNdsCell = String.Format("{0}*{1}", countCell.Address, priceNdsCell.Address);
                                sumNdsCell.FormulaR1C1 = formulaSumNdsCell;
                                sumNdsCell.Style.NumberFormat.Format = "₽ #,##0.00";
                                sumNdsCell.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right);
                                // /> Сумма с НДС

                                //workSheet.Cell(row, 5).Value = !calculation.PriceCurrency.Equals(0)
                                //    ? calculation.PriceCurrency.ToString("N2")
                                //    : string.Empty;
                                //workSheet.Cell(row, 6).Value = !calculation.SumCurrency.Equals(0)
                                //    ? calculation.SumCurrency.ToString("N2")
                                //    : string.Empty;
                                //workSheet.Cell(row, 7).Value = "";//currencies.First(x => x.Id == calculation.Currency).Value;
                                //workSheet.Cell(row, 7).Value = !calculation.PriceRub.Equals(0)
                                //    ? calculation.PriceRub.ToString("N2")
                                //    : string.Empty;
                                //workSheet.Cell(row, 8).Value = !calculation.SumRub.Equals(0)
                                //    ? calculation.SumRub.ToString("N2")
                                //    : string.Empty;

                                workSheet.Cell(row, ++col).Value = calculation.Provider;
                                workSheet.Cell(row, col)
                                    .Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                                //workSheet.Cell(row, 9).Value = calculation.ProtectFact != null ?
                                //    facts.First(x => x.Id == calculation.ProtectFact.Id).Value : String.Empty;
                                //workSheet.Cell(row, 10).Value = calculation.ProtectCondition;
                                workSheet.Cell(row, ++col).Value = calculation.Comment;
                                workSheet.Cell(row, col).Style.Font.SetFontColor(XLColor.Red);
                                double hComent = GetCellHeight(workSheet.Cell(row, col).Value.ToString().Length, 40);

                                double[] arr = { hPosCatNum, hPosName, hCalcName, hCalcDeliv, hProdManager, hComent, hCalcCatNum };
                                workSheet.Row(row).Height = arr.Max();
                                row++;
                                rowNumber++;
                            }
                        }

                        else
                        {
                            int col = 0;
                            workSheet.Cell(row, ++col).Value = rowNumber;
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            workSheet.Cell(row, ++col).Value = position.CatalogNumber;
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);

                            workSheet.Cell(row, ++col).SetValue(position.Name);
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Left);

                            workSheet.Row(row).Height = GetCellHeight(position.CatalogNumber.Length, 10);
                            workSheet.Row(row).Height = GetCellHeight(position.Name.Length, 40);
                            ++col;
                            ++col;
                            //workSheet.Cell(row, ++col).Value = String.Empty;
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Left);
                            workSheet.Cell(row, ++col).Value = GetUnitStr(position.Unit);
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            workSheet.Cell(row, ++col).Value = position.Value;
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            if (position.ProductManager != null)
                            {
                                var prodManager = UserHelper.GetUserById(position.ProductManager.Id);
                                workSheet.Cell(row, ++col).Value = prodManager == null
                                    ? String.Empty
                                    : prodManager.ShortName;
                            }
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            workSheet.Cell(row, ++col).Value = String.Empty;
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);

                            ++col;//Цена B2B

                            workSheet.Cell(row, ++col).Value = String.Empty;
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            workSheet.Cell(row, col).Style.NumberFormat.Format = "$ #,###";
                            workSheet.Cell(row, ++col).Value = String.Empty;
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            workSheet.Cell(row, col).Style.NumberFormat.Format = "€ #,###";
                            workSheet.Cell(row, ++col).Value = String.Empty;
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            workSheet.Cell(row, col).Style.NumberFormat.Format = "€ #,###";
                            workSheet.Cell(row, ++col).Value = String.Empty;
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            workSheet.Cell(row, col).Style.NumberFormat.Format = "₽ #,###";
                            col = col + 6;
                            workSheet.Cell(row, col).Value = String.Empty;
                            workSheet.Cell(row, col).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            row++;
                            rowNumber++;
                        }
                    }

                    var range = workSheet.Range(workSheet.Cell(firstRow, 1), workSheet.Cell(row - 1, 21));
                    range.Style.Border.SetBottomBorder(XLBorderStyleValues.Thin);
                    range.Style.Border.SetBottomBorderColor(XLColor.Gray);
                    range.Style.Border.SetTopBorder(XLBorderStyleValues.Thin);
                    range.Style.Border.SetTopBorderColor(XLColor.Gray);
                    range.Style.Border.SetRightBorder(XLBorderStyleValues.Thin);
                    range.Style.Border.SetRightBorderColor(XLColor.Gray);
                    range.Style.Border.SetLeftBorder(XLBorderStyleValues.Thin);
                    range.Style.Border.SetLeftBorderColor(XLColor.Gray);

                    excBook.SaveAs(ms);
                    excBook.Dispose();
                    ms.Seek(0, SeekOrigin.Begin);
                }
                else
                {
                    error = true;
                    message = "Нет позиций для расчета";
                }
            }
            catch (Exception ex)
            {
                error = true;
                message = "Ошибка сервера " + ex.Message;
            }
            finally
            {
                if (excBook != null)
                {
                    excBook.Dispose();
                }
            }
            if (!error)
            {
                return new FileStreamResult(ms, "application/vnd.ms-excel")
                {
                    FileDownloadName = "Calculation_" + claimId + ".xlsx"
                };
            }
            else
            {
                ViewBag.Message = message;
                return View();
            }
        }
        //Excel
        //получение excel файла с инфой по позициям и расчетам к ним
        public ActionResult GetSpecificationFile(int claimId, bool forManager, int cv)
        {
            XLWorkbook excBook = null;
            var ms = new MemoryStream();
            var error = false;
            var message = string.Empty;
            try
            {
                var user = GetUser();
                var db = new DbEngine();
                var positions = new List<SpecificationPosition>();
                //получение позиций исходя из роли юзера
                if (UserHelper.IsController(user) || UserHelper.IsManager(user))
                {
                    positions = db.LoadSpecificationPositionsForTenderClaim(claimId, cv);
                }
                else
                {
                    if (UserHelper.IsProductManager(user))
                    {
                        positions = db.LoadSpecificationPositionsForTenderClaimForProduct(claimId, user.Id, cv);
                    }
                }
                if (positions.Any())
                {
                    //if (forManager) positions = positions.Where(x => x.State == 2 || x.State == 4).ToList();
                    //else positions = positions.Where(x => x.State == 1 || x.State == 3).ToList();
                    if (positions.Any())
                    {
                        //расчет к позициям
                        var calculations = db.LoadCalculateSpecificationPositionsForTenderClaim(claimId, cv);
                        if (calculations != null && calculations.Any())
                        {
                            foreach (var position in positions)
                            {
                                if (UserHelper.IsManager(user) && position.State == 1 && !UserHelper.IsController(user) && !UserHelper.IsProductManager(user)) continue;
                                position.Calculations =
                                    calculations.Where(x => x.IdSpecificationPosition == position.Id).ToList();
                            }
                        }
                        var filePath = Path.Combine(Server.MapPath("~"), "App_Data", "Template.xlsx");
                        using (var fs = System.IO.File.OpenRead(filePath))
                        {
                            var buffer = new byte[fs.Length];
                            fs.Read(buffer, 0, buffer.Count());
                            ms.Write(buffer, 0, buffer.Count());
                            ms.Seek(0, SeekOrigin.Begin);
                        }
                        //создание excel файла
                        excBook = new XLWorkbook(ms);
                        var workSheet = excBook.Worksheet("WorkSheet");
                        workSheet.Name = "Расчет";
                        var claim = db.LoadTenderClaimById(claimId);
                        //>>>>>>>>Шапка - Заполнение инфы о заявке<<<<<<
                        var dealTypes = db.LoadDealTypes();
                        var manager = UserHelper.GetUserById(claim.Manager.Id);
                        //workSheet.Cell(1, 3).Value = !claim.CurrencyUsd.Equals(0)
                        //    ? claim.CurrencyUsd.ToString("N2")
                        //    : string.Empty;
                        //workSheet.Cell(2, 3).Value = !claim.CurrencyEur.Equals(0)
                        //    ? claim.CurrencyEur.ToString("N2")
                        //    : string.Empty;
                        //workSheet.Cell(1, 3).DataType = XLCellValues.Number;
                        //workSheet.Cell(2, 3).DataType = XLCellValues.Number;
                        workSheet.Cell(1, 4).Value = claim.TenderNumber;
                        //workSheet.Cell(4, 3).Value = claim.TenderStartString;
                        //workSheet.Cell(4, 3).DataType = XLCellValues.DateTime;
                        //workSheet.Cell(5, 3).Value = claim.ClaimDeadlineString;
                        //workSheet.Cell(5, 3).DataType = XLCellValues.DateTime;
                        //workSheet.Cell(6, 3).Value = claim.KPDeadlineString;
                        //workSheet.Cell(6, 3).DataType = XLCellValues.DateTime;
                        workSheet.Cell(2, 4).Value = claim.Customer;
                        //workSheet.Cell(8, 3).Value = claim.CustomerInn;
                        //workSheet.Cell(9, 3).Value = !claim.Sum.Equals(0) ? claim.Sum.ToString("N2") : string.Empty;
                        //workSheet.Cell(10, 3).Value = dealTypes.First(x => x.Id == claim.DealType).Value;
                        //workSheet.Cell(11, 3).Value = claim.TenderUrl;
                        workSheet.Cell(3, 4).Value = manager != null ? manager.ShortName : string.Empty;
                        //workSheet.Cell(13, 3).Value = claim.Manager.SubDivision;
                        //workSheet.Cell(14, 3).Value = claim.DeliveryDateString;
                        //workSheet.Cell(14, 3).DataType = XLCellValues.DateTime;
                        //workSheet.Cell(15, 3).Value = claim.DeliveryPlace;
                        //workSheet.Cell(16, 3).Value = claim.AuctionDateString;
                        //workSheet.Cell(16, 3).DataType = XLCellValues.DateTime;
                        //workSheet.Cell(17, 3).Value = claim.Comment;
                        var directRangeSheet = excBook.AddWorksheet("Справочники");
                        //создание дипазона выбора значений Факт получения защиты
                        var facts = db.LoadProtectFacts();
                        //var currencies = db.LoadCurrencies();
                        var deliveryTimes = db.LoadDeliveryTimes();

                        var deliveryTimesList = deliveryTimes.Select(x => x.Value).ToList();
                        for (var i = 0; i < deliveryTimesList.Count(); i++)
                        {
                            var time = deliveryTimesList[i];
                            var cell = directRangeSheet.Cell(i + 1, 3);
                            if (cell != null)
                            {
                                cell.Value = time;
                            }
                        }

                        var protectFactList = facts.Select(x => x.Value).ToList();
                        for (var i = 0; i < protectFactList.Count(); i++)
                        {
                            var protectFact = protectFactList[i];
                            var cell = directRangeSheet.Cell(i + 1, 1);
                            if (cell != null)
                            {
                                cell.Value = protectFact;
                            }
                        }

                        //var availableCurrencies = currencies.Where(x => x.Value.ToLowerInvariant() != "руб").ToList();
                        //for (var i = 0; i < currencies.Count(); i++)
                        //{
                        //    var currency = currencies[i];
                        //    var cell = directRangeSheet.Cell(i + 1, 2);
                        //    if (cell != null)
                        //    {
                        //        cell.Value = currency.Value;
                        //    }
                        //}

                        var protectFactRange = directRangeSheet.Range(directRangeSheet.Cell(1, 1),
                            directRangeSheet.Cell(protectFactList.Count(), 1));
                        //var currenciesRange = directRangeSheet.Range(directRangeSheet.Cell(1, 2),
                        //    directRangeSheet.Cell(currencies.Count(), 2));
                        var deliveryTimeRange = directRangeSheet.Range(directRangeSheet.Cell(1, 3),
                            directRangeSheet.Cell(deliveryTimes.Count(), 3));

                        directRangeSheet.Visibility = XLWorksheetVisibility.Hidden;
                        //>>>>>>>номер строки начало вывода инфы<<<<<<
                        var row = 4;

                        //В первой колонке храним id шники
                        workSheet.Column(1).Hide();

                        //вывод инфы по позициям
                        //workSheet.Cell(row, 2).Value = "Запрос";

                        //заголовок для строк расчета
                        //workSheet.Cell(row, 3).Value = "Каталожный номер*";
                        //workSheet.Cell(row, 4).Value = "Наименование*";
                        //workSheet.Cell(row, 5).Value = "Замена";
                        //workSheet.Cell(row, 6).Value = "Цена USD";
                        //workSheet.Cell(row, 7).Value = "Цена EUR";
                        //workSheet.Cell(row, 8).Value = "Цена EUR Ricoh";
                        //workSheet.Cell(row, 9).Value = "Цена руб";
                        //workSheet.Cell(row, 10).Value = "Поставщик";
                        //workSheet.Cell(row, 11).Value = "Срок поставки";
                        //workSheet.Cell(row, 12).Value = "Факт защиты*";
                        //workSheet.Cell(row, 13).Value = "Условия защиты";
                        //workSheet.Cell(row, 14).Value = "Комментарий";
                        //workSheet.Range(workSheet.Cell(row, 2), workSheet.Cell(row, 14)).Style.Font.SetBold(true);
                        var posCounter = 0;

                        foreach (var position in positions)
                        {
                            //заголовок и данные по позиции

                            //workSheet.Cell(row, 1).Value = "Каталожный номер";
                            //workSheet.Cell(row, 2).Value = "Наименование";
                            //workSheet.Cell(row, 3).Value = "Замена";
                            //workSheet.Cell(row, 3).Value = "Единица";
                            //workSheet.Cell(row, 4).Value = "Количество";
                            //workSheet.Cell(row, 5).Value = "Комментарий";
                            //workSheet.Cell(row, 7).Value = "Сумма, максимум";
                            //workSheet.Cell(row, 8).Value = "Id";
                            //workSheet.Cell(row, 9).Value = "Сумма с ТЗР";
                            //workSheet.Cell(row, 10).Value = "Сумма с НДС";

                            row++;

                            var idCell = workSheet.Cell(row, 1);
                            idCell.Value = position.Id;
                            workSheet.Cell(row, 2).Value = ++posCounter;
                            workSheet.Cell(row, 2).Style.Font.SetBold();
                            workSheet.Cell(row, 2).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            workSheet.Cell(row, 2).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Center);

                            workSheet.Cell(row, 3).Value = position.CatalogNumber;
                            var posCell = workSheet.Cell(row, 4);
                            posCell.Value = String.Format("{2}\r\n{5}", position.Id, position.CatalogNumber, position.Name, GetUnitString(position.Unit), position.Value, position.Comment);
                            posCell.Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);
                            posCell.Style.Alignment.SetWrapText();
                            workSheet.Row(row).AdjustToContents();

                            workSheet.Cell(row, 5).Value = String.Format("{1} {0}", GetUnitString(position.Unit),
                                position.Value);

                            //Объединяем две ячейки чтобы удобнее было добавлять строки пользователям руками
                            workSheet.Range(workSheet.Cell(row, 1), workSheet.Cell(row + 1, 1)).Merge();
                            workSheet.Range(workSheet.Cell(row, 2), workSheet.Cell(row + 1, 2)).Merge();
                            workSheet.Range(workSheet.Cell(row, 3), workSheet.Cell(row + 1, 3)).Merge();
                            workSheet.Range(workSheet.Cell(row, 4), workSheet.Cell(row + 1, 4)).Merge();
                            workSheet.Range(workSheet.Cell(row, 5), workSheet.Cell(row + 1, 5)).Merge();
                            //workSheet.Rows(row, row+1).AdjustToContents();

                            //workSheet.Cell(row, 1).Value = position.CatalogNumber;
                            //workSheet.Cell(row, 2).Value = position.Name;
                            ////workSheet.Cell(row, 3).Value = position.Replace;
                            //workSheet.Cell(row, 3).Value = GetUnitString(position.Unit);
                            //workSheet.Cell(row, 4).Value = position.Value;
                            //workSheet.Cell(row, 5).Value = position.Comment;
                            //var currency = currencies.First(x => x.Id == position.Currency);
                            //workSheet.Cell(row, 7).Value = !position.Sum.Equals(0)
                            //    ? position.Sum.ToString("N2") + " " + currency.Value
                            //    : string.Empty;
                            //workSheet.Cell(row, 9).Value = !position.Sum.Equals(0)
                            //    ? position.SumTzr.ToString("N2") + " " + currency.Value
                            //    : string.Empty;
                            //workSheet.Cell(row, 10).Value = !position.Sum.Equals(0)
                            //    ? position.SumNds.ToString("N2") + " " + currency.Value
                            //    : string.Empty;
                            //workSheet.Cell(row, 8).Value = position.Id;
                            //var positionRange = workSheet.Range(workSheet.Cell(row - 1, 1), workSheet.Cell(row, 5));
                            //positionRange.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            //positionRange.Style.Border.SetBottomBorder(XLBorderStyleValues.Thin);
                            //positionRange.Style.Border.SetBottomBorderColor(XLColor.Gray);
                            //positionRange.Style.Border.SetTopBorder(XLBorderStyleValues.Thin);
                            //positionRange.Style.Border.SetTopBorderColor(XLColor.Gray);
                            //positionRange.Style.Border.SetRightBorder(XLBorderStyleValues.Thin);
                            //positionRange.Style.Border.SetRightBorderColor(XLColor.Gray);
                            //positionRange.Style.Border.SetLeftBorder(XLBorderStyleValues.Thin);
                            //positionRange.Style.Border.SetLeftBorderColor(XLColor.Gray);
                            //positionRange.Style.Fill.BackgroundColor = XLColor.FromArgb(0, 204, 233, 255);
                            //row++;
                            ////заголовок для строк расчета
                            //workSheet.Cell(row, 1).Value = "Каталожный номер*";
                            //workSheet.Cell(row, 2).Value = "Наименование*";
                            //workSheet.Cell(row, 3).Value = "Замена";
                            //workSheet.Cell(row, 4).Value = "Цена за ед.";
                            //workSheet.Cell(row, 5).Value = "Сумма вход";
                            //workSheet.Cell(row, 6).Value = "Валюта";
                            ////workSheet.Cell(row, 7).Value = "Цена за ед. руб";
                            ////workSheet.Cell(row, 9).Value = "Сумма вход руб*";
                            //workSheet.Cell(row, 7).Value = "Поставщик";
                            //workSheet.Cell(row, 8).Value = "callHd";
                            //workSheet.Cell(row, 9).Value = "Факт получ.защиты*";
                            //workSheet.Cell(row, 10).Value = "Условия защиты";
                            //workSheet.Cell(row, 11).Value = "Комментарий";
                            //var calcHeaderRange = workSheet.Range(workSheet.Cell(row, 1), workSheet.Cell(row, 11));
                            //calcHeaderRange.Style.Font.SetBold(true);
                            //calcHeaderRange.Style.Fill.BackgroundColor = XLColor.FromArgb(0, 204, 255, 209);
                            //calcHeaderRange.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            //calcHeaderRange.Style.Border.SetBottomBorder(XLBorderStyleValues.Thin);
                            //calcHeaderRange.Style.Border.SetBottomBorderColor(XLColor.Gray);
                            //calcHeaderRange.Style.Border.SetTopBorder(XLBorderStyleValues.Thin);
                            //calcHeaderRange.Style.Border.SetTopBorderColor(XLColor.Gray);
                            //calcHeaderRange.Style.Border.SetRightBorder(XLBorderStyleValues.Thin);
                            //calcHeaderRange.Style.Border.SetRightBorderColor(XLColor.Gray);
                            //calcHeaderRange.Style.Border.SetLeftBorder(XLBorderStyleValues.Thin);
                            //calcHeaderRange.Style.Border.SetLeftBorderColor(XLColor.Gray);

                            var firstPosRow = row;
                            //вывод инфы по расчету к позиции
                            if (position.Calculations != null && position.Calculations.Any())
                            {
                                var calcCount = 1;

                                foreach (var calculation in position.Calculations)
                                {
                                    ExcelDataFormatCalcRow(ref workSheet, row, deliveryTimeRange, protectFactRange);

                                    if (calcCount > 1)
                                    {
                                        row++;

                                        ExcelDataFormatCalcRow(ref workSheet, row, deliveryTimeRange, protectFactRange);

                                        workSheet.Range(workSheet.Cell(firstPosRow, 1), workSheet.Cell(row, 1)).Merge();
                                        workSheet.Range(workSheet.Cell(firstPosRow, 2), workSheet.Cell(row, 2)).Merge();
                                        workSheet.Range(workSheet.Cell(firstPosRow, 3), workSheet.Cell(row, 3)).Merge();
                                        workSheet.Range(workSheet.Cell(firstPosRow, 4), workSheet.Cell(row , 4)).Merge();
                                        workSheet.Range(workSheet.Cell(firstPosRow, 5), workSheet.Cell(row, 5)).Merge();
                                    }

                                    workSheet.Cell(row, 6).Value = calculation.CatalogNumber;
                                    workSheet.Cell(row, 7).Value = calculation.Name;
                                    workSheet.Cell(row, 7).Style.Alignment.SetWrapText();
                                    workSheet.Cell(row, 8).Value = calculation.Replace;
                                    workSheet.Cell(row, 8).Style.Alignment.SetWrapText();

                                    workSheet.Cell(row, 9).Value = calculation.PriceUsd;
                                    workSheet.Cell(row, 10).Value = calculation.PriceEur;
                                    workSheet.Cell(row, 11).Value = calculation.PriceEurRicoh;
                                    workSheet.Cell(row, 12).Value = calculation.PriceRubl;
                                    workSheet.Cell(row, 13).Value = calculation.Provider;
                                    workSheet.Cell(row, 13).Style.Alignment.SetWrapText();

                                    if (calculation.DeliveryTime != null) workSheet.Cell(row, 14).Value = deliveryTimes.First(x => x.Id == calculation.DeliveryTime.Id).Value;
                                    workSheet.Cell(row, 14).Style.Alignment.SetWrapText();

                                    if (calculation.ProtectFact != null) workSheet.Cell(row, 15).Value = facts.First(x => x.Id == calculation.ProtectFact.Id).Value;

                                    workSheet.Cell(row, 16).Value = calculation.ProtectCondition;
                                    workSheet.Cell(row, 16).Style.Alignment.SetWrapText();
                                    workSheet.Cell(row, 17).Value = calculation.Comment;
                                    workSheet.Cell(row, 17).Style.Alignment.SetWrapText();

                                    calcCount++;
                                }

                                //foreach (var calculation in position.Calculations)
                                //{
                                //    row++;
                                //    workSheet.Cell(row, 1).Value = calculation.CatalogNumber;
                                //    workSheet.Cell(row, 2).Value = calculation.Name;
                                //    workSheet.Cell(row, 3).Value = calculation.Replace;
                                //    workSheet.Cell(row, 4).Value = !calculation.PriceCurrency.Equals(0)
                                //        ? calculation.PriceCurrency.ToString("N2")
                                //        : string.Empty;
                                //    workSheet.Cell(row, 5).Value = !calculation.SumCurrency.Equals(0)
                                //        ? calculation.SumCurrency.ToString("N2")
                                //        : string.Empty;
                                //    var validation = workSheet.Cell(row, 6).SetDataValidation();
                                //    validation.AllowedValues = XLAllowedValues.List;
                                //    validation.InCellDropdown = true;
                                //    validation.Operator = XLOperator.Between;
                                //    validation.List(currenciesRange);
                                //    workSheet.Cell(row, 6).Value =
                                //        currencies.First(x => x.Id == calculation.Currency).Value;
                                //    //workSheet.Cell(row, 7).Value = !calculation.PriceRub.Equals(0)
                                //    //    ? calculation.PriceRub.ToString("N2")
                                //    //    : string.Empty;
                                //    //workSheet.Cell(row, 9).Value = !calculation.SumRub.Equals(0)
                                //    //    ? calculation.SumRub.ToString("N2")
                                //    //    : string.Empty;
                                //    workSheet.Cell(row, 7).Value = calculation.Provider;
                                //    validation = workSheet.Cell(row, 9).SetDataValidation();
                                //    validation.AllowedValues = XLAllowedValues.List;
                                //    validation.InCellDropdown = true;
                                //    validation.Operator = XLOperator.Between;
                                //    validation.List(protectFactRange);
                                //    workSheet.Cell(row, 9).Value =
                                //        facts.First(x => x.Id == calculation.ProtectFact.Id).Value;
                                //    workSheet.Cell(row, 10).Value = calculation.ProtectCondition;
                                //    workSheet.Cell(row, 11).Value = calculation.Comment;
                                //}
                            }
                            else
                            {

                                //var validation = workSheet.Cell(row, 12).SetDataValidation();
                                //validation.AllowedValues = XLAllowedValues.List;
                                //validation.InCellDropdown = true;
                                //validation.Operator = XLOperator.Between;
                                //validation.List(deliveryTimeRange);

                                //validation = workSheet.Cell(row, 13).SetDataValidation();
                                //validation.AllowedValues = XLAllowedValues.List;
                                //validation.InCellDropdown = true;
                                //validation.Operator = XLOperator.Between;
                                //validation.List(protectFactRange);

                                ExcelDataFormatCalcRow(ref workSheet, row, deliveryTimeRange, protectFactRange);
                                //Специально добавляем строчу так как мы делаем специально две на позицию чтобы ыбло удобнее добавлять руками в Экселе
                                row++;
                                ExcelDataFormatCalcRow(ref workSheet, row, deliveryTimeRange, protectFactRange);

                                //row++;
                                //var validation = workSheet.Cell(row, 6).SetDataValidation();
                                //validation.AllowedValues = XLAllowedValues.List;
                                //validation.InCellDropdown = true;
                                //validation.Operator = XLOperator.Between;
                                //validation.List(currenciesRange);
                                //validation = workSheet.Cell(row, 9).SetDataValidation();
                                //validation.AllowedValues = XLAllowedValues.List;
                                //validation.InCellDropdown = true;
                                //validation.Operator = XLOperator.Between;
                                //validation.List(protectFactRange);
                            }
                            //row++;
                        }

                        var list = workSheet.Range(workSheet.Cell(4, 1), workSheet.Cell(row, 17));

                        list.Style.Border.SetBottomBorder(XLBorderStyleValues.Thin);
                        list.Style.Border.SetBottomBorderColor(XLColor.Gray);
                        list.Style.Border.SetTopBorder(XLBorderStyleValues.Thin);
                        list.Style.Border.SetTopBorderColor(XLColor.Gray);
                        list.Style.Border.SetRightBorder(XLBorderStyleValues.Thin);
                        list.Style.Border.SetRightBorderColor(XLColor.Gray);
                        list.Style.Border.SetLeftBorder(XLBorderStyleValues.Thin);
                        list.Style.Border.SetLeftBorderColor(XLColor.Gray);

                        //workSheet.Columns(1, 11).AdjustToContents();
                        //workSheet.Column(8).Hide();
                        excBook.SaveAs(ms);
                        excBook.Dispose();
                        ms.Seek(0, SeekOrigin.Begin);
                    }
                    else
                    {
                        error = true;
                        message = "Нет позиций для расчета";
                    }
                }
                else
                {
                    error = true;
                    message = "Нет позиций для расчета";
                }
            }
            catch (Exception)
            {
                error = true;
                message = "Ошибка сервера";
            }
            finally
            {
                if (excBook != null)
                {
                    excBook.Dispose();
                }
            }
            if (!error)
            {
                return new FileStreamResult(ms, "application/vnd.ms-excel")
                {
                    FileDownloadName = "Specification_" + claimId + ".xlsx"
                };
            }
            else
            {
                ViewBag.Message = message;
                return View();
            }
        }
        //Excel
        //получение excel файла, для определения позиций по заявке
        public ActionResult GetSpecificationFile(int claimId)
        {
            XLWorkbook excBook = null;
            var ms = new MemoryStream();
            var error = false;
            try
            {
                var db = new DbEngine();
                var claim = db.LoadTenderClaimById(claimId);
                //получение файла-шаблона
                var filePath = Path.Combine(Server.MapPath("~"), "App_Data", "Specification.xlsx");
                using (var fs = System.IO.File.OpenRead(filePath))
                {
                    var buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Count());
                    ms.Write(buffer, 0, buffer.Count());
                    ms.Seek(0, SeekOrigin.Begin);
                }
                //создание диапазона выбора снабженцев
                var productManagers = UserHelper.GetProductManagers();
                excBook = new XLWorkbook(ms);
                var workSheet = excBook.Worksheet("Лот");
                var userRangeSheet = excBook.Worksheet(2);

                if (workSheet != null && userRangeSheet != null)
                {
                    userRangeSheet.Visibility = XLWorksheetVisibility.Hidden;
                    //>>>>>>>>Шапка - Заполнение инфы о заявке<<<<<<
                    var dealTypes = db.LoadDealTypes();

                    var manager = UserHelper.GetUserById(claim.Manager.Id);
                    //workSheet.Cell(1, 3).Value = !claim.CurrencyUsd.Equals(0)
                    //    ? claim.CurrencyUsd.ToString("N2")
                    //    : string.Empty;
                    //workSheet.Cell(2, 3).Value = !claim.CurrencyEur.Equals(0)
                    //    ? claim.CurrencyEur.ToString("N2")
                    //    : string.Empty;
                    //workSheet.Cell(1, 3).DataType = XLCellValues.Number;
                    //workSheet.Cell(2, 3).DataType = XLCellValues.Number;
                    workSheet.Cell(1, 3).Value = claim.TenderNumber;
                    //workSheet.Cell(4, 3).Value = claim.TenderStartString;
                    //workSheet.Cell(4, 3).DataType = XLCellValues.DateTime;
                    //workSheet.Cell(5, 3).Value = claim.ClaimDeadlineString;
                    //workSheet.Cell(5, 3).DataType = XLCellValues.DateTime;
                    //workSheet.Cell(6, 3).Value = claim.KPDeadlineString;
                    //workSheet.Cell(6, 3).DataType = XLCellValues.DateTime;
                    workSheet.Cell(2, 3).Value = claim.Customer;
                    //workSheet.Cell(8, 3).Value = claim.CustomerInn;
                    //workSheet.Cell(9, 3).Value = !claim.Sum.Equals(0) ? claim.Sum.ToString("N2") : string.Empty;
                    //workSheet.Cell(10, 3).Value = dealTypes.First(x => x.Id == claim.DealType).Value;
                    //workSheet.Cell(11, 3).Value = claim.TenderUrl;
                    workSheet.Cell(3, 3).Value = manager != null ? manager.ShortName : string.Empty;
                    //workSheet.Cell(13, 3).Value = claim.Manager.SubDivision;
                    //workSheet.Cell(14, 3).Value = claim.DeliveryDateString;
                    //workSheet.Cell(14, 3).DataType = XLCellValues.DateTime;
                    //workSheet.Cell(15, 3).Value = claim.DeliveryPlace;
                    //workSheet.Cell(16, 3).Value = claim.AuctionDateString;
                    //workSheet.Cell(16, 3).DataType = XLCellValues.DateTime;
                    //workSheet.Cell(17, 3).Value = claim.Comment;
                    for (var i = 0; i < productManagers.Count(); i++)
                    {
                        var product = productManagers[i];
                        var cell = userRangeSheet.Cell(i + 1, 2);
                        if (cell != null)
                        {
                            cell.Value = GetUniqueDisplayName(product);
                        }
                    }
                    var namedRange = userRangeSheet.Range(userRangeSheet.Cell(1, 2), userRangeSheet.Cell(productManagers.Count(), 2));
                    //var currencies = db.LoadCurrencies();
                    //for (var i = 0; i < currencies.Count(); i++)
                    //{
                    //    var currency = currencies[i];
                    //    var cell = userRangeSheet.Cell(i + 1, 3);
                    //    if (cell != null)
                    //    {
                    //        cell.Value = currency.Value;
                    //    }
                    //}
                    //var currenciesRange = userRangeSheet.Range(userRangeSheet.Cell(1, 3), userRangeSheet.Cell(currencies.Count(), 3));
                    var workRange = workSheet.Cell(5, 6);
                    if (workRange != null)
                    {
                        var validation = workRange.SetDataValidation();
                        validation.AllowedValues = XLAllowedValues.List;
                        validation.InCellDropdown = true;
                        validation.Operator = XLOperator.Between;
                        validation.List(namedRange);
                    }
                    //workRange = workSheet.Cell(14, 8);
                    //if (workRange != null)
                    //{
                    //    var validation = workRange.SetDataValidation();
                    //    validation.AllowedValues = XLAllowedValues.List;
                    //    validation.InCellDropdown = true;
                    //    validation.Operator = XLOperator.Between;
                    //    validation.List(currenciesRange);
                    //}
                    userRangeSheet.Visibility = XLWorksheetVisibility.Hidden;
                    workSheet.Select();
                    //workSheet.Column(3).AdjustToContents();
                    //workSheet.Column(6).Style.Alignment.WrapText = true;
                    excBook.SaveAs(ms);
                }
                excBook.Dispose();
                excBook = null;
                ms.Seek(0, SeekOrigin.Begin);

            }
            catch (Exception)
            {
                error = true;
            }
            finally
            {
                if (excBook != null)
                {
                    excBook.Dispose();
                }
            }
            if (!error)
            {
                return new FileStreamResult(ms, "application/vnd.ms-excel")
                {
                    FileDownloadName = "Specification.xlsx"
                };
            }
            else
            {
                return View();
            }
        }
Example #8
0
    public string make_efile(string department_code, string datefrom, string dateto)
    {
        try
        {
            if (HttpContext.Current.Session["username"] == null)
            {
                return "<span style='color:red'>Session Time-out. Please Log-in Again</span>";

            }
        }
        catch (Exception ex)
        {
            return "<span style='color:red'>Session Time-out. Please Log-in Again</span>";

        }

        string filename = "Nutratech_DTR.xlsx";
        //_" & Date.Now.ToString("MMddyyyy") & "
        string x = "";

        if (File.Exists(Server.MapPath("~\\pdf\\" + HttpContext.Current.Session["username"] + "\\") + filename))
        {
            try
            {
                File.Delete(Server.MapPath("~\\pdf\\" + HttpContext.Current.Session["username"] + "\\") + filename);

            }
            catch (Exception ex)
            {
            }
        }

        // Create the workbook
        XLWorkbook workbook = new XLWorkbook();
        IXLWorksheet worksheet = workbook.Worksheets.Add("Nutratech DTR " + System.DateTime.Now.ToString("MMM yyyy"));

        worksheet.Cell(1, 1).SetValue("NUTRATECH BIOPHARMA INC.");
        worksheet.Cell(1, 1).Style.Font.Bold = true;
        worksheet.Cell(1, 1).Style.Font.FontSize = 12;
        worksheet.Cell(1, 1).Style.Font.FontName = "Calibri";

        worksheet.Cell(2, 1).SetValue("DAILY TIME RECORD MONITORING FORM");
        worksheet.Cell(2, 1).Style.Font.FontSize = 11;
        worksheet.Cell(2, 1).Style.Font.FontName = "Calibri";

        worksheet.Cell(3, 1).SetValue("DATE RANGE : " + datefrom + " - " + dateto);
        worksheet.Cell(3, 1).Style.Font.FontSize = 11;
        worksheet.Cell(3, 1).Style.Font.FontName = "Calibri";

        worksheet.Cell(4, 1).SetValue("DEPARTMENT : " + ExcelReport.hr_department_Descs(department_code));
        worksheet.Cell(4, 1).Style.Font.FontSize = 11;
        worksheet.Cell(4, 1).Style.Font.FontName = "Calibri";

        worksheet.Cell(1, 7).SetValue("LOG TYPE LEGEND : ");
        worksheet.Cell(1, 7).Style.Font.FontSize = 10;
        worksheet.Cell(1, 7).Style.Font.Bold = true;
        worksheet.Cell(1, 7).Style.Font.FontName = "Calibri";

        worksheet.Cell(1, 8).SetValue("OB - Official Business");
        worksheet.Cell(1, 8).Style.Font.FontSize = 10;
        worksheet.Cell(1, 8).Style.Font.FontName = "Calibri";

        worksheet.Cell(2, 8).SetValue("CT - Change of Timekeeping");
        worksheet.Cell(2, 8).Style.Font.FontSize = 10;
        worksheet.Cell(2, 8).Style.Font.FontName = "Calibri";

        worksheet.Column(1).Width = 5;
        worksheet.Column(2).Width = 15;
        worksheet.Column(3).Width = 30;
        worksheet.Column(4).Width = 15;
        worksheet.Column(5).Width = 15;
        worksheet.Column(6).Width = 15;
        worksheet.Column(7).Width = 15;
        worksheet.Column(8).Width = 10;
        worksheet.Column(9).Width = 30;
        worksheet.Column(10).Width = 20;

        int xrow = 6;
        int xcol = 1;

        //============================================================================================
        xcol = 1;
        worksheet.Cell(xrow, xcol).SetValue("No.");
        worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
        worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
        worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        worksheet.Cell(xrow, xcol).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
        worksheet.Range("A" + xrow + ":B" + (xrow + 1).ToString()).Column(1).Merge();
        worksheet.Range("A" + xrow + ":B" + (xrow + 1).ToString()).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        worksheet.Range("A" + xrow + ":B" + (xrow + 1).ToString()).Style.Border.BottomBorder = XLBorderStyleValues.Double;
        worksheet.Range("A" + xrow + ":B" + (xrow + 1).ToString()).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        worksheet.Range("A" + xrow + ":B" + (xrow + 1).ToString()).Style.Border.RightBorder = XLBorderStyleValues.Thin;

        xcol = 2;
        worksheet.Cell(xrow, xcol).SetValue("Employee ID");
        worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
        worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
        worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        worksheet.Cell(xrow, xcol).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
        worksheet.Range("B" + xrow + ":C" + (xrow + 1).ToString()).Column(1).Merge();
        worksheet.Range("B" + xrow + ":C" + (xrow + 1).ToString()).Column(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        worksheet.Range("B" + xrow + ":C" + (xrow + 1).ToString()).Column(1).Style.Border.BottomBorder = XLBorderStyleValues.Double;
        worksheet.Range("B" + xrow + ":C" + (xrow + 1).ToString()).Column(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        worksheet.Range("B" + xrow + ":C" + (xrow + 1).ToString()).Column(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

        xcol = 3;
        worksheet.Cell(xrow, xcol).SetValue("Name");
        worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
        worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
        worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        worksheet.Cell(xrow, xcol).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
        worksheet.Range("C" + xrow + ":D" + (xrow + 1).ToString()).Column(1).Merge();
        worksheet.Range("C" + xrow + ":D" + (xrow + 1).ToString()).Column(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        worksheet.Range("C" + xrow + ":D" + (xrow + 1).ToString()).Column(1).Style.Border.BottomBorder = XLBorderStyleValues.Double;
        worksheet.Range("C" + xrow + ":D" + (xrow + 1).ToString()).Column(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        worksheet.Range("C" + xrow + ":D" + (xrow + 1).ToString()).Column(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

        xcol = 4;
        worksheet.Cell(xrow, xcol).Value = "AM";
        worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
        worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
        worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        worksheet.Range("D" + xrow + ":E" + xrow).Row(1).Merge();
        worksheet.Range("D" + xrow + ":E" + xrow).Row(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        worksheet.Range("D" + xrow + ":E" + xrow).Row(1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
        worksheet.Range("D" + xrow + ":E" + xrow).Row(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        worksheet.Range("D" + xrow + ":E" + xrow).Row(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

        xcol = 6;
        worksheet.Cell(xrow, xcol).Value = "PM";
        worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
        worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
        worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        worksheet.Range("F" + xrow + ":G" + xrow).Row(1).Merge();
        worksheet.Range("F" + xrow + ":G" + xrow).Row(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        worksheet.Range("F" + xrow + ":G" + xrow).Row(1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
        worksheet.Range("F" + xrow + ":G" + xrow).Row(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        worksheet.Range("F" + xrow + ":G" + xrow).Row(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

        xcol = 8;
        worksheet.Cell(xrow, xcol).SetValue("Log Type");
        worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
        worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
        worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        worksheet.Cell(xrow, xcol).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
        worksheet.Range("H" + xrow + ":I" + (xrow + 1).ToString()).Column(1).Merge();
        worksheet.Range("H" + xrow + ":I" + (xrow + 1).ToString()).Column(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        worksheet.Range("H" + xrow + ":I" + (xrow + 1).ToString()).Column(1).Style.Border.BottomBorder = XLBorderStyleValues.Double;
        worksheet.Range("H" + xrow + ":I" + (xrow + 1).ToString()).Column(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        worksheet.Range("H" + xrow + ":I" + (xrow + 1).ToString()).Column(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

        xcol = 9;
        worksheet.Cell(xrow, xcol).SetValue("Remarks");
        worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
        worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
        worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        worksheet.Cell(xrow, xcol).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
        worksheet.Range("I" + xrow + ":J" + (xrow + 1).ToString()).Column(1).Merge();
        worksheet.Range("I" + xrow + ":J" + (xrow + 1).ToString()).Column(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        worksheet.Range("I" + xrow + ":J" + (xrow + 1).ToString()).Column(1).Style.Border.BottomBorder = XLBorderStyleValues.Double;
        worksheet.Range("I" + xrow + ":J" + (xrow + 1).ToString()).Column(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        worksheet.Range("I" + xrow + ":J" + (xrow + 1).ToString()).Column(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

        xcol = 10;
        worksheet.Cell(xrow, xcol).SetValue("Signature");
        worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
        worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
        worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        worksheet.Cell(xrow, xcol).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
        worksheet.Range("J" + xrow + ":K" + (xrow + 1).ToString()).Column(1).Merge();
        worksheet.Range("J" + xrow + ":K" + (xrow + 1).ToString()).Column(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        worksheet.Range("J" + xrow + ":K" + (xrow + 1).ToString()).Column(1).Style.Border.BottomBorder = XLBorderStyleValues.Double;
        worksheet.Range("J" + xrow + ":K" + (xrow + 1).ToString()).Column(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        worksheet.Range("J" + xrow + ":K" + (xrow + 1).ToString()).Column(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

        //============================================================================================
        xrow += 1;

        xcol = 4;
        worksheet.Cell(xrow, xcol).SetValue("Time In");
        worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
        worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
        worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        worksheet.Cell(xrow, xcol).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        worksheet.Cell(xrow, xcol).Style.Border.BottomBorder = XLBorderStyleValues.Double;
        worksheet.Cell(xrow, xcol).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        worksheet.Cell(xrow, xcol).Style.Border.RightBorder = XLBorderStyleValues.Thin;

        xcol = 5;
        worksheet.Cell(xrow, xcol).SetValue("Time Out");
        worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
        worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
        worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        worksheet.Cell(xrow, xcol).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        worksheet.Cell(xrow, xcol).Style.Border.BottomBorder = XLBorderStyleValues.Double;
        worksheet.Cell(xrow, xcol).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        worksheet.Cell(xrow, xcol).Style.Border.RightBorder = XLBorderStyleValues.Thin;

        xcol = 6;
        worksheet.Cell(xrow, xcol).SetValue("Time In");
        worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
        worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
        worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        worksheet.Cell(xrow, xcol).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        worksheet.Cell(xrow, xcol).Style.Border.BottomBorder = XLBorderStyleValues.Double;
        worksheet.Cell(xrow, xcol).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        worksheet.Cell(xrow, xcol).Style.Border.RightBorder = XLBorderStyleValues.Thin;

        xcol = 7;
        worksheet.Cell(xrow, xcol).SetValue("Time Out");
        worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
        worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
        worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        worksheet.Cell(xrow, xcol).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        worksheet.Cell(xrow, xcol).Style.Border.BottomBorder = XLBorderStyleValues.Double;
        worksheet.Cell(xrow, xcol).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        worksheet.Cell(xrow, xcol).Style.Border.RightBorder = XLBorderStyleValues.Thin;

        //============================================================================================
        xrow += 1;

        int f_date_year = Convert.ToDateTime(datefrom).Year;
        int f_date_month = Convert.ToDateTime(datefrom).Month;
        int f_date_day = Convert.ToDateTime(datefrom).Day;

        int t_date_year = Convert.ToDateTime(dateto).Year;
        int t_date_month = Convert.ToDateTime(dateto).Month;
        int t_date_day = Convert.ToDateTime(dateto).Day;

        bool _loop = false;
        string xdate = "";

        for (int i = f_date_year; i <= t_date_year; i++)
        {

            if (i < t_date_year)
            {
                for (int ii = f_date_month; ii <= 12; ii++)
                {
                    if (ii <= 12)
                    {
                        if (_loop == true)
                        {
                            int end_month_day = ExcelReport.get_end_day(ii, i);
                            for (int iii = 1; iii <= end_month_day; iii++)
                            {
                                xdate = ii.ToString("00") + "/" + iii.ToString("00") + "/" + i.ToString("0000");
                                _loop = true;

                                //============================================================================================

                                xcol = 1;
                                worksheet.Cell(xrow, xcol).SetValue(Convert.ToDateTime(xdate).ToLongDateString());
                                worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
                                worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
                                worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
                                worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Merge();
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

                                xrow += 1;
                                xrow = ExcelReport.xstr_excelfile(worksheet, department_code, xdate, xrow);

                                xrow += 2;
                            }
                        }
                        else
                        {
                            int end_month_day = ExcelReport.get_end_day(ii, i);
                            for (int iii = f_date_day; iii <= end_month_day; iii++)
                            {
                                xdate = ii.ToString("00") + "/" + iii.ToString("00") + "/" + i.ToString("0000");
                                _loop = true;

                                //============================================================================================

                                xcol = 1;
                                worksheet.Cell(xrow, xcol).SetValue(Convert.ToDateTime(xdate).ToLongDateString());
                                worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
                                worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
                                worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
                                worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Merge();
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

                                xrow += 1;
                                xrow = ExcelReport.xstr_excelfile(worksheet, department_code, xdate, xrow);

                                xrow += 2;
                            }
                        }
                    }
                }

            }
            else if (i == t_date_year)
            {
                if (_loop == true)
                {
                    for (int ii = 1; ii <= t_date_month; ii++)
                    {
                        if (ii < t_date_month)
                        {
                            int end_month_day = ExcelReport.get_end_day(ii, i);
                            for (int iii = 1; iii <= end_month_day; iii++)
                            {
                                xdate = ii.ToString("00") + "/" + iii.ToString("00") + "/" + i.ToString("0000");
                                _loop = true;

                                //============================================================================================

                                xcol = 1;
                                worksheet.Cell(xrow, xcol).SetValue(Convert.ToDateTime(xdate).ToLongDateString());
                                worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
                                worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
                                worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
                                worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Merge();
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

                                xrow += 1;
                                xrow = ExcelReport.xstr_excelfile(worksheet, department_code, xdate, xrow);

                                xrow += 2;
                            }
                        }
                        else if (ii == t_date_month)
                        {
                            for (int iii = 1; iii <= t_date_day; iii++)
                            {
                                xdate = ii.ToString("00") + "/" + iii.ToString("00") + "/" + i.ToString("0000");
                                _loop = true;

                                //============================================================================================

                                xcol = 1;
                                worksheet.Cell(xrow, xcol).SetValue(Convert.ToDateTime(xdate).ToLongDateString());
                                worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
                                worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
                                worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
                                worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Merge();
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                                worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

                                xrow += 1;
                                xrow = ExcelReport.xstr_excelfile(worksheet, department_code, xdate, xrow);

                                xrow += 2;
                            }
                        }
                    }
                }
                else
                {
                    for (int ii = f_date_month; ii <= t_date_month; ii++)
                    {
                        if (ii < t_date_month)
                        {
                            if (_loop == true)
                            {
                                int end_month_day = ExcelReport.get_end_day(ii, i);
                                for (int iii = 1; iii <= end_month_day; iii++)
                                {
                                    xdate = ii.ToString("00") + "/" + iii.ToString("00") + "/" + i.ToString("0000");
                                    _loop = true;

                                    //============================================================================================

                                    xcol = 1;
                                    worksheet.Cell(xrow, xcol).SetValue(Convert.ToDateTime(xdate).ToLongDateString());
                                    worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
                                    worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
                                    worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
                                    worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Merge();
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

                                    xrow += 1;
                                    xrow = ExcelReport.xstr_excelfile(worksheet, department_code, xdate, xrow);

                                    xrow += 2;
                                }
                            }
                            else
                            {
                                int end_month_day = ExcelReport.get_end_day(ii, i);
                                for (int iii = f_date_day; iii <= end_month_day; iii++)
                                {
                                    xdate = ii.ToString("00") + "/" + iii.ToString("00") + "/" + i.ToString("0000");
                                    _loop = true;

                                    //============================================================================================

                                    xcol = 1;
                                    worksheet.Cell(xrow, xcol).SetValue(Convert.ToDateTime(xdate).ToLongDateString());
                                    worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
                                    worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
                                    worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
                                    worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Merge();
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

                                    xrow += 1;
                                    xrow = ExcelReport.xstr_excelfile(worksheet, department_code, xdate, xrow);

                                    xrow += 2;
                                }
                            }

                        }
                        else if (ii == t_date_month)
                        {
                            if (_loop == true)
                            {
                                for (int iii = 1; iii <= t_date_day; iii++)
                                {
                                    xdate = ii.ToString("00") + "/" + iii.ToString("00") + "/" + i.ToString("0000");
                                    _loop = true;

                                    //============================================================================================

                                    xcol = 1;
                                    worksheet.Cell(xrow, xcol).SetValue(Convert.ToDateTime(xdate).ToLongDateString());
                                    worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
                                    worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
                                    worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
                                    worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Merge();
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

                                    xrow += 1;
                                    xrow = ExcelReport.xstr_excelfile(worksheet, department_code, xdate, xrow);

                                    xrow += 2;
                                }
                            }
                            else
                            {
                                for (int iii = f_date_day; iii <= t_date_day; iii++)
                                {
                                    xdate = ii.ToString("00") + "/" + iii.ToString("00") + "/" + i.ToString("0000");
                                    _loop = true;

                                    //============================================================================================

                                    xcol = 1;
                                    worksheet.Cell(xrow, xcol).SetValue(Convert.ToDateTime(xdate).ToLongDateString());
                                    worksheet.Cell(xrow, xcol).Style.Font.FontSize = 10;
                                    worksheet.Cell(xrow, xcol).Style.Font.Bold = true;
                                    worksheet.Cell(xrow, xcol).Style.Font.FontName = "Calibri";
                                    worksheet.Cell(xrow, xcol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Merge();
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.TopBorder = XLBorderStyleValues.Thin;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                                    worksheet.Range("A" + xrow + ":J" + xrow).Row(1).Style.Border.RightBorder = XLBorderStyleValues.Thin;

                                    xrow += 1;
                                    xrow = ExcelReport.xstr_excelfile(worksheet, department_code, xdate, xrow);

                                    xrow += 2;
                                }
                            }
                        }
                    }
                }
            }

        }

        worksheet.Cell(xrow, 1).SetValue("****** End of File ******");
        worksheet.Cell(xrow, 1).Style.Font.FontSize = 10;
        worksheet.Cell(xrow, 1).Style.Font.FontName = "Calibri";

        workbook.SaveAs(Server.MapPath("~\\pdf\\" + HttpContext.Current.Session["username"] + "\\") + filename);

        worksheet.Dispose();
        workbook.Dispose();
        x = "Daily Time Record Generated...";

        return x;
    }
Example #9
0
    public string read_excel_header()
    {
        try
        {
            if (HttpContext.Current.Session["username"] == null)
            {
                return "<span style='color:red'>Session Time-out. Please Log-in Again</span>";

            }
        }
        catch (Exception ex)
        {
            return "<span style='color:red'>Session Time-out. Please Log-in Again</span>";

        }

        string x = "";
        string filename = Server.MapPath("~\\pdf\\" + HttpContext.Current.Session["username"] + "\\Nutratech_DTR.xlsx");

        StringBuilder sb = new StringBuilder();

        if (File.Exists(filename))
        {
            XLWorkbook workbook = new XLWorkbook(filename);
            IXLWorksheet ws = workbook.Worksheet(1);

            IXLCell cell = ws.Cell(4, 1);
            string cell_department = cell.GetString();

            cell = ws.Cell(3, 1);
            string cell_daterange = cell.GetString();
            cell_daterange = cell_daterange.Replace("DATE RANGE : ", "");

            sb.Append("[");
            sb.Append("{");

            try
            {
                sb.Append("\"department\":\"" + cell_department.Replace("DEPARTMENT : ", "") + "\",");
            }
            catch (Exception ex)
            {
                sb.Append("\"department\":\"" + "" + "\",");
            }
            try
            {
                sb.Append("\"date_from\":\"" + cell_daterange.Substring(0, cell_daterange.IndexOf(" - ")).Trim() + "\",");
            }
            catch (Exception ex)
            {
                sb.Append("\"date_from\":\"" + "" + "\",");
            }
            try
            {
                sb.Append("\"date_to\":\"" + cell_daterange.Substring(cell_daterange.IndexOf(" - ") + 3).Trim() + "\"");
            }
            catch (Exception ex)
            {
                sb.Append("\"date_to\":\"" + "" + "\"");
            }

            sb.Append("}");

            sb.Append("]");
            ws.Dispose();
            workbook.Dispose();

        }

        return sb.ToString();
    }
Example #10
0
        // 创建读者详情 Excel 文件。这是便于被外部调用的版本,只需要提供读者 XML 记录即可
        // return:
        //      -1  出错
        //      0   用户中断
        //      1   成功
        public static int CreateReaderDetailExcelFile(List<string> xmls,
            Delegate_GetBiblioSummary procGetBiblioSummary,
            Stop stop,
            bool bAdvanceXml,
            bool bLaunchExcel,
            out string strError)
        {
            strError = "";
            //int nRet = 0;

            ExportPatronExcelDialog dlg = new ExportPatronExcelDialog();
            MainForm.SetControlFont(dlg, Program.MainForm.Font, false);
            dlg.UiState = Program.MainForm.AppInfo.GetString(
        "ReaderSearchForm",
        "ExportPatronExcelDialog_uiState",
        "");

            Program.MainForm.AppInfo.LinkFormState(dlg, "ReaderSearchForm_ExportPatronExcelDialog_uiState_state");
            dlg.ShowDialog(Program.MainForm);

            Program.MainForm.AppInfo.SetString(
"ReaderSearchForm",
"ExportPatronExcelDialog_uiState",
dlg.UiState);

            if (dlg.DialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                strError = "放弃操作";
                return 0;
            }

            string strTimeRange = "";

            try
            {
                strTimeRange = GetTimeRange(dlg.ChargingHistoryDateRange);
            }
            catch (Exception ex)
            {
                strError = "日期范围字符串 '" + dlg.ChargingHistoryDateRange + "' 格式不合法: " + ex.Message;
                return -1;
            }

#if NO
            // 询问文件名
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Title = "请指定要输出的 Excel 文件名";
            dlg.CreatePrompt = false;
            dlg.OverwritePrompt = true;
            // dlg.FileName = this.ExportExcelFilename;
            // dlg.InitialDirectory = Environment.CurrentDirectory;
            dlg.Filter = "Excel 文件 (*.xlsx)|*.xlsx|All files (*.*)|*.*";

            dlg.RestoreDirectory = true;

            if (dlg.ShowDialog() != DialogResult.OK)
                return 0;
#endif

            XLWorkbook doc = null;

            try
            {
                doc = new XLWorkbook(XLEventTracking.Disabled);
                File.Delete(dlg.FileName);
            }
            catch (Exception ex)
            {
                strError = "ReaderSearchForm new XLWorkbook() {0BD1CB34-DF8A-4DDB-B884-8A9CF830D7C7} exception: " + ExceptionUtil.GetAutoText(ex);
                return -1;
            }

            IXLWorksheet sheet = null;
            sheet = doc.Worksheets.Add("表格");

            try
            {
                if (stop != null)
                    stop.SetProgressRange(0, xmls.Count);

                // 每个列的最大字符数
                List<int> column_max_chars = new List<int>();

                // TODO: 表的标题,创建时间

                int nRowIndex = 3;  // 空出前两行
                //int nColIndex = 1;

                int nReaderIndex = 0;
                foreach (string strXml in xmls)
                {
                    Application.DoEvents();	// 出让界面控制权

                    if (stop != null && stop.State != 0)
                        return 0;

                    if (string.IsNullOrEmpty(strXml) == true)
                        continue;

                    XmlDocument dom = new XmlDocument();
                    try
                    {
                        dom.LoadXml(strXml);
                    }
                    catch (Exception ex)
                    {
                        strError = "装载读者记录 XML 到 DOM 时发生错误: " + ex.Message;
                        return -1;
                    }

                    string strBarcode = DomUtil.GetElementText(dom.DocumentElement, "barcode");

                    // 
                    if (dlg.ExportReaderInfo)
                    {
                        OutputReaderInfo(sheet,
                dom,
                nReaderIndex,
                ref nRowIndex,
                ref column_max_chars);
                    }

                    // 输出在借册表格
                    if (dlg.ExportBorrowInfo)
                    {
                        OutputBorrows(sheet,
                dom,
                procGetBiblioSummary,
                bAdvanceXml,
                ref nRowIndex,
                ref column_max_chars);
                    }

                    // 输出违约金表格
                    if (dlg.ExportOverdueInfo)
                    {
                        OutputOverdues(sheet,
                dom,
                procGetBiblioSummary,
                ref nRowIndex,
                ref column_max_chars);
                    }

                    if (dlg.ExportChargingHistory)
                    {
                        LibraryChannel channel = Program.MainForm.GetChannel();
                        try
                        {
                            ChargingHistoryLoader history_loader = new ChargingHistoryLoader();
                            history_loader.Channel = channel;
                            history_loader.Stop = stop;
                            history_loader.PatronBarcode = strBarcode;
                            history_loader.TimeRange = strTimeRange;
                            history_loader.Actions = "return,lost";
                            history_loader.Order = "descending";

                            CacheableBiblioLoader summary_loader = new CacheableBiblioLoader();
                            summary_loader.Channel = channel;
                            summary_loader.Stop = stop;
                            summary_loader.Format = "summary";
                            summary_loader.GetBiblioInfoStyle = GetBiblioInfoStyle.None;
                            // summary_loader.RecPaths = biblio_recpaths;

                            // 输出借阅历史表格
                            // 可能会抛出异常,例如权限不够
                            OutputBorrowHistory(sheet,
                    dom,
                    history_loader,
                                // this.MainForm.GetBiblioSummary,
                    summary_loader,
                    ref nRowIndex,
                    ref column_max_chars);
                        }
                        catch (Exception ex)
                        {
                            strError = "输出借阅历史时出现异常: " + ex.Message;
                            return -1;
                        }
                        finally
                        {
                            Program.MainForm.ReturnChannel(channel);
                        }
                    }

                    nRowIndex++;    // 读者之间的空行

                    nReaderIndex++;
                    if (stop != null)
                        stop.SetProgressValue(nReaderIndex);
                }

                {
                    if (stop != null)
                        stop.SetMessage("正在调整列宽度 ...");
                    Application.DoEvents();

                    // 字符数太多的列不要做 width auto adjust
                    foreach (IXLColumn column in sheet.Columns())
                    {
                        int MAX_CHARS = 50;   // 60

                        int nIndex = column.FirstCell().Address.ColumnNumber - 1;
                        if (nIndex >= column_max_chars.Count)
                            break;
                        int nChars = column_max_chars[nIndex];

                        if (nIndex == 1)
                        {
                            column.Width = 10;
                            continue;
                        }

                        if (nIndex == 3)
                            MAX_CHARS = 50;
                        else
                            MAX_CHARS = 24;

                        if (nChars < MAX_CHARS)
                            column.AdjustToContents();
                        else
                            column.Width = Math.Min(MAX_CHARS, nChars);
                    }
                }
            }
            finally
            {
                if (doc != null)
                {
                    doc.SaveAs(dlg.FileName);
                    doc.Dispose();
                }

                if (bLaunchExcel)
                {
                    try
                    {
                        System.Diagnostics.Process.Start(dlg.FileName);
                    }
                    catch
                    {

                    }
                }

            }
            return 1;
        }
        public void Cabecera_OP_Grafica(string nomarchivo)
        {
            ////// ClosedXML ////////
            XLWorkbook oWB = new XLWorkbook(nomarchivo);
            var oSheet = oWB.Worksheet(1);

            switch (_Estado.ToUpper())
            {
                case "ORDENADO":
                    {
                        EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);
                        OrdenadoCabDTO miCabecera = (OrdenadoCabDTO)_Cabecera;
                        DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));

                        string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                        string aniomes = miCabecera.AnoMes.ToString();

                        oSheet.Cells("C6").Value = "" + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);
                        oSheet.Cells("C7").Value = medio.Name;
                        oSheet.Cells("C8").Value = _Espacio.Name;
                        oSheet.Cells("C9").Value = _Espacio.Telefono == null ? "" : _Espacio.Telefono;
                        oSheet.Cells("C10").Value = _Espacio.Contacto == null ? "" : _Espacio.Contacto.ToUpper();
                        oSheet.Cells("D14").Value = "MES: " + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);
                        oSheet.Cells("F25").Value = _Espacio.Responsable == null ? "" : _Espacio.Responsable.ToUpper();

                        SetUpDTO setup = new SetUpDTO();
                        string sector = setup.Sector;

                        oSheet.Cells("F26").Value = sector;
                        oSheet.Cells("F27").Value = empresa.Name;
                        oSheet.Cells("F28").Value = empresa.Leyenda;

                        break;
                    }
            
                case "ESTIMADO": {

                    EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);
                    EstimadoCabDTO miCabecera = (EstimadoCabDTO)_Cabecera;
                    DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));

                    string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                    string aniomes = miCabecera.AnoMes.ToString();

                    oSheet.Cells("C6").Value = "" + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);
                    oSheet.Cells("C7").Value = medio.Name;
                    oSheet.Cells("C8").Value = _Espacio.Name;
                    oSheet.Cells("C9").Value = _Espacio.Telefono == null ? "" : _Espacio.Telefono;
                    oSheet.Cells("C10").Value = _Espacio.Contacto == null ? "" : _Espacio.Contacto.ToUpper();
                    oSheet.Cells("D14").Value = "MES: " + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);
                    oSheet.Cells("F25").Value = _Espacio.Responsable == null ? "" : _Espacio.Responsable.ToUpper();

                    SetUpDTO setup = new SetUpDTO();
                    string sector = setup.Sector;

                    oSheet.Cells("F26").Value = sector;
                    oSheet.Cells("F27").Value = empresa.Name;
                    oSheet.Cells("F28").Value = empresa.Leyenda;
                    
                    break; }

                case "CERTIFICADO":
                    {
                        EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);
                        CertificadoCabDTO miCabecera = (CertificadoCabDTO)_Cabecera;
                        DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));

                        string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                        string aniomes = miCabecera.AnoMes.ToString();

                        oSheet.Cells("C6").Value = "" + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);
                        oSheet.Cells("C7").Value = medio.Name;
                        oSheet.Cells("C8").Value = _Espacio.Name;
                        oSheet.Cells("C9").Value = _Espacio.Telefono == null ? "" : _Espacio.Telefono;
                        oSheet.Cells("C10").Value = _Espacio.Contacto == null ? "" : _Espacio.Contacto.ToUpper();
                        oSheet.Cells("D14").Value = "MES: " + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);
                        oSheet.Cells("F25").Value = _Espacio.Responsable == null ? "" : _Espacio.Responsable.ToUpper();

                        SetUpDTO setup = new SetUpDTO();
                        string sector = setup.Sector;

                        oSheet.Cells("F26").Value = sector;
                        oSheet.Cells("F27").Value = empresa.Name;
                        oSheet.Cells("F28").Value = empresa.Leyenda;

                        break;
                    }
            }

            oWB.SaveAs(nomarchivo);
            oWB.Dispose();
            oSheet = null;
            oWB = null;
            GC.Collect(); 
        }
        public void Detalle_OP_Calendario_Numerico(string nomArchivo)
        {
            ////// ClosedXML ////////
            XLWorkbook oWB = new XLWorkbook(nomArchivo);
            var oSheet = oWB.Worksheet(1);

            int iDia = 0;
            int DiasEnMes = 0;
            string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
            string[] DiasSemana = { "", "L", "M", "M", "J", "V", "S", "D" };
            int[] DiasPautados = new int[10];
            int ocurrencias = 0;
            int MaxLines = 0;
            List<string> IdentifAvisos = new List<string>();

            switch (_Estado.ToUpper())
            {
                case "ORDENADO":
                    {
                        OrdenadoCabDTO miCabecera = (OrdenadoCabDTO)_Cabecera;
                        List<OrdenadoDetDTO> miDetalle = (List<OrdenadoDetDTO>)_Detalle;
                        miDetalle = miDetalle.OrderBy(P => P.Dia).ThenBy(Q => Q.Hora).ThenBy(R => R.Salida).ToList();
                        int DiaDelAnio = miDetalle[0].Fecha.DayOfYear;
                        string aniomes = miCabecera.AnoMes.ToString();
                        int mes = Convert.ToInt32(aniomes.Substring(4, 2));
                        int anio = Convert.ToInt32(aniomes.Substring(0, 4));
                        DiasEnMes = System.DateTime.DaysInMonth(anio, mes);
                        DiasPautados = new int[DiasEnMes + 1];
                        int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                        int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);
                        int dia = PrimerDiaMes - PrimerDiaSemana + 2;

                        iDia = PrimerDiaSemana;

                        for (int x = 1; x <= DiasEnMes; x++)
                        {
                            for (int j = 0; j <= miDetalle.Count - 1; j++)
                            {
                                if (miDetalle[j].Fecha.Day == x)
                                {
                                    DiasPautados[x]++;
                                }
                            }
                        }

                        iDia = PrimerDiaSemana;

                        //CALCULA LA MAXIMA CANTIDAD DE SALIDAS DE AVISOS
                        MaxLines = 0;

                        for (int k = 0; k <= DiasPautados.Length - 1; k++)
                        {
                            if (DiasPautados[k] > MaxLines)
                            {
                                MaxLines = DiasPautados[k];
                            }
                        }



                        IdentifAvisos.Add(miDetalle[0].IdentifAviso);

                        bool lencontrado = false;

                        for (int i = 0; i <= miDetalle.Count - 1; i++)
                        {
                            lencontrado = false;

                            for(int j = 0; j<=IdentifAvisos.Count-1;j++)
                            {
                                if (IdentifAvisos[j] == miDetalle[i].IdentifAviso)
                                {
                                    lencontrado = true;

                                    break;

                                }
                            }

                            if (!lencontrado)
                            {
                                IdentifAvisos.Add(miDetalle[i].IdentifAviso);

                            }
                        }


                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {

                            int cantsal = 0;

                            for (int j = 0; j <= miDetalle.Count - 1; j++)
                            {
                                if (miDetalle[j].IdentifAviso == IdentifAvisos[i])
                                {

                                    int ThisDay = (int)miDetalle[j].Dia;
                                    ocurrencias = 0;

                                    for (int k = 0; k <= miDetalle.Count - 1; k++)
                                    {
                                        if ((int)miDetalle[k].Dia == ThisDay && miDetalle[k].IdentifAviso == IdentifAvisos[i])
                                        {
                                            ocurrencias++;
                                        }
                                    }

                                    cantsal++;
                                }
                            }
                        }


                        //LIMPIEZA DE DIAS Y FECHAS
                        for (int i = 1; i <= 31; i++)
                        {
                            oSheet.Cell(18, 2 + i).Value = "";
                            oSheet.Cell(19, 2 + i).Value = "";
                        }

                        for (int i = 1; i <= (DiasEnMes); i++)
                        {
                            oSheet.Cell(18, 2 + i).Value = DiasSemana[iDia].ToUpper();
                            oSheet.Cell(19, 2 + i).Value = i;

                            iDia++;

                            if (iDia == 8)
                            {
                                iDia = 1;
                            }
                        }
                        /// FIN ARMADO CALENDARIO ///
                        /// 

                        /////////////////
                        //EMPIEZO A ARMAR FRAME PARA CADA UNO DE LOS PRODUCTOS

                        var xlSourceRange = oSheet.Range("B17:AK22");


                        for (int i = 1; i <= IdentifAvisos.Count - 1; i++)
                        {
                            var rng = oSheet.Range("B16:AK16");
                            rng.InsertRowsBelow(6);
                        }

                        int Fila = 17;

                        for (int i = 1; i <= IdentifAvisos.Count - 1; i++)
                        {
                            oSheet.Cell(Fila, 2).Value = xlSourceRange;

                            Fila = Fila + 6;
                        }


                        ////// CUENTO OCURRENCIAS X AVISO PARA INSERTAR LAS LINEAS RESEPECIIVAS /////

                        int[] FilasProducto = new int[IdentifAvisos.Count];

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            for (int diaMes = 1; diaMes <= DiasEnMes - 1; diaMes++)
                            {
                                ocurrencias = 0;

                                for (int k = 0; k <= miDetalle.Count - 1; k++)
                                {
                                    if (miDetalle[k].IdentifAviso == IdentifAvisos[i] && miDetalle[k].Fecha.Day == diaMes && miDetalle[k].Fecha.Month == mes)
                                    {
                                        ocurrencias++;
                                    }

                                }

                                if (ocurrencias > 0)
                                {
                                    if (ocurrencias > FilasProducto[i])
                                    {
                                        FilasProducto[i] = ocurrencias;
                                    }
                                }


                            }
                        }

                        //inserta filas en cada uno de los productos de acuerdo a lo que hay en filasproducto
                        Fila = 20;

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            var rng = oSheet.Range("B" + Fila.ToString() + ":AK" + Fila.ToString());

                            rng.InsertRowsBelow(FilasProducto[i]-1);

                            Fila += 6 + Convert.ToInt32(FilasProducto[i]-1);
                        }

                        ////// comienzo a rellenar con valores //

                        Fila = 17;

                        for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                        {
                            AvisosDTO aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[j].ToString()));

                            oSheet.Cell(Fila, 3).Value = aviso.EtiquetaProd;

                            Fila += 6 + FilasProducto[j]-1;
                        }


                        Fila = 20;
                        int FilaPosicional = 20;

                        string[] Celdas = { "", "", "", "C", "D", "E", "F", "G", "H", "I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG" };

                        miDetalle = miDetalle.OrderBy(p => p.Dia).ThenBy(q => q.Hora).ThenBy(r => r.Salida).ToList();

                        for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                        {
                            for (int k = 1; k <= DiasEnMes; k++)
                            {

                                oSheet.Column(k + 2).Width = 3;

                                for (int l = 0; l <= miDetalle.Count - 1; l++)
                                {
                                    
                                    if (miDetalle[l].Fecha.Day == k &&
                                        miDetalle[l].Fecha.Month == mes &&
                                        miDetalle[l].IdentifAviso == IdentifAvisos[j])
                                    {
                                        oSheet.Cell(Fila, k + 2).Value = 1;

                                        int sumDesde = FilaPosicional;
                                        int sumHasta = FilaPosicional + FilasProducto[j]-1;

                                        string Formula = string.Format("=+SUM({0}{1}:{2}{3})", Celdas[k + 2].ToString(), sumDesde.ToString(), Celdas[k + 2].ToString(), sumHasta.ToString());

                                        oSheet.Cell(FilaPosicional + FilasProducto[j], k + 2).FormulaA1 = Formula;

                                        Fila++;
                                    }

                                }

                                Fila = FilaPosicional;
                            }

                            FilaPosicional = Fila += 6 + FilasProducto[j]-1;

                        }


                        //// SUBTOTALES DE CADA COLUMNA /////

                        int[] STP = new int[DiasEnMes + 1];
                        int[] STT = new int[DiasEnMes + 1];

                        FilaPosicional = 15;

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            FilaPosicional = FilaPosicional + 5 + FilasProducto[i];

                            for (int j = 1; j <= DiasEnMes; j++)
                            {
                                if (oSheet.Cell(FilaPosicional, j + 2).Value.ToString() == "")
                                {
                                    STP[j] = Convert.ToInt32(oSheet.Cell(FilaPosicional, j + 2).Value + "0");
                                }
                                else
                                {
                                    STP[j] = Convert.ToInt32(oSheet.Cell(FilaPosicional, j + 2).Value);
                                }

                                STT[j] += STP[j];
                            }
                        }

                        FilaPosicional += 2;

                        for (int j = 1; j <= DiasEnMes; j++)
                        {
                            oSheet.Cell(FilaPosicional, j + 2).Value = STT[j];
                        }

                        ////// LLENO MARGEN DERECHO CON TOTALES ////////////

                        FilaPosicional = 15;

                        decimal CostoTotal = 0;
                        decimal GrandTotal = 0;
                        int UnidadesTotales = 0;

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            FilaPosicional = FilaPosicional + 5;

                            for(int j=0;j<=FilasProducto[i]-1;j++)
                            {
                                oSheet.Cell("AH" + FilaPosicional.ToString()).FormulaA1 = string.Format("=SUM({0}{1}:{2}{3})", "C",FilaPosicional ,"AG", FilaPosicional);

                                for (int k = 0; k <= miDetalle.Count - 1; k++)
                                {
                                    if (miDetalle[k].IdentifAviso == IdentifAvisos[i])
                                    {
                                        oSheet.Cell("AI" + FilaPosicional.ToString()).Value = miDetalle[k].CostoOp;
                                        oSheet.Cell("AJ" + FilaPosicional.ToString()).Value = miDetalle[k].Duracion;
                                        oSheet.Cell("AK" + FilaPosicional.ToString()).Value = Convert.ToDecimal(oSheet.Cell("AH" + FilaPosicional.ToString()).Value) * Convert.ToDecimal(oSheet.Cell("AI" + FilaPosicional.ToString()).Value);  

                                        CostoTotal += Convert.ToDecimal(oSheet.Cell("AK" + FilaPosicional.ToString()).Value);

                                        break;
                                    }
                                }

                                oSheet.Cell("AK" + FilaPosicional.ToString()).Value = Convert.ToDecimal(oSheet.Cell("AH" + FilaPosicional.ToString()).Value) * Convert.ToDecimal(oSheet.Cell("AI" + FilaPosicional.ToString()).Value);  

                                FilaPosicional++;

                            }

                            oSheet.Cell("AH" + FilaPosicional.ToString()).FormulaA1 = string.Format("=SUM({0}{1}:{2}{3})", "C", FilaPosicional, "AG", FilaPosicional);
                            oSheet.Cell("AI" + FilaPosicional.ToString()).Value = "";
                            oSheet.Cell("AJ" + FilaPosicional.ToString()).Value = "";
                            oSheet.Cell("AK" + FilaPosicional.ToString()).Value = CostoTotal;

                            GrandTotal += CostoTotal;

                            UnidadesTotales += Convert.ToInt32(oSheet.Cell("AH" + FilaPosicional.ToString()).Value);

                            CostoTotal = 0;

                        }

                        FilaPosicional += 2;

                        oSheet.Cell("AH" + FilaPosicional.ToString()).Value = UnidadesTotales;
                        oSheet.Cell("AK" + FilaPosicional.ToString()).Value = GrandTotal;

                        FilaPosicional += 3;

                        oSheet.Cell("AI" + FilaPosicional.ToString()).Value = _Espacio.Responsable;


                        DAO.SetUpDAO STUP = new DAO.SetUpDAO();

                        SetUpDTO setup = STUP.Read(1);

                        oSheet.Cell("AI" + (FilaPosicional + 1).ToString()).Value = setup.Sector;

                        EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);

                        oSheet.Cell("AI" + (FilaPosicional + 2).ToString()).Value = empresa.Name;

                        ////////////////////////////////////////////////////
                        
                        break;
                    }

                case "ESTIMADO":
                    {
                        EstimadoCabDTO miCabecera = (EstimadoCabDTO)_Cabecera;
                        List<EstimadoDetDTO> miDetalle = (List<EstimadoDetDTO>)_Detalle;
                        miDetalle = miDetalle.OrderBy(P => P.Dia).ThenBy(Q => Q.Hora).ThenBy(R => R.Salida).ToList();
                        int DiaDelAnio = miDetalle[0].Fecha.DayOfYear;
                        string aniomes = miCabecera.AnoMes.ToString();
                        int mes = Convert.ToInt32(aniomes.Substring(4, 2));
                        int anio = Convert.ToInt32(aniomes.Substring(0, 4));
                        DiasEnMes = System.DateTime.DaysInMonth(anio, mes);
                        DiasPautados = new int[DiasEnMes + 1];
                        int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                        int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);
                        int dia = PrimerDiaMes - PrimerDiaSemana + 2;

                        iDia = PrimerDiaSemana;

                        for (int x = 1; x <= DiasEnMes; x++)
                        {
                            for (int j = 0; j <= miDetalle.Count - 1; j++)
                            {
                                if (miDetalle[j].Fecha.Day == x)
                                {
                                    DiasPautados[x]++;
                                }
                            }
                        }

                        iDia = PrimerDiaSemana;

                        //CALCULA LA MAXIMA CANTIDAD DE SALIDAS DE AVISOS
                        MaxLines = 0;

                        for (int k = 0; k <= DiasPautados.Length - 1; k++)
                        {
                            if (DiasPautados[k] > MaxLines)
                            {
                                MaxLines = DiasPautados[k];
                            }
                        }



                        IdentifAvisos.Add(miDetalle[0].IdentifAviso);

                        bool lencontrado = false;

                        for (int i = 0; i <= miDetalle.Count - 1; i++)
                        {
                            lencontrado = false;

                            for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                            {
                                if (IdentifAvisos[j] == miDetalle[i].IdentifAviso)
                                {
                                    lencontrado = true;

                                    break;

                                }
                            }

                            if (!lencontrado)
                            {
                                IdentifAvisos.Add(miDetalle[i].IdentifAviso);

                            }
                        }


                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {

                            int cantsal = 0;

                            for (int j = 0; j <= miDetalle.Count - 1; j++)
                            {
                                if (miDetalle[j].IdentifAviso == IdentifAvisos[i])
                                {

                                    int ThisDay = (int)miDetalle[j].Dia;
                                    ocurrencias = 0;

                                    for (int k = 0; k <= miDetalle.Count - 1; k++)
                                    {
                                        if ((int)miDetalle[k].Dia == ThisDay && miDetalle[k].IdentifAviso == IdentifAvisos[i])
                                        {
                                            ocurrencias++;
                                        }
                                    }

                                    cantsal++;
                                }
                            }
                        }


                        //LIMPIEZA DE DIAS Y FECHAS
                        for (int i = 1; i <= 31; i++)
                        {
                            oSheet.Cell(18, 2 + i).Value = "";
                            oSheet.Cell(19, 2 + i).Value = "";
                        }

                        for (int i = 1; i <= (DiasEnMes); i++)
                        {
                            oSheet.Cell(18, 2 + i).Value = DiasSemana[iDia].ToUpper();
                            oSheet.Cell(19, 2 + i).Value = i;

                            iDia++;

                            if (iDia == 8)
                            {
                                iDia = 1;
                            }
                        }
                        /// FIN ARMADO CALENDARIO ///
                        /// 

                        /////////////////
                        //EMPIEZO A ARMAR FRAME PARA CADA UNO DE LOS PRODUCTOS

                        var xlSourceRange = oSheet.Range("B17:AK22");


                        for (int i = 1; i <= IdentifAvisos.Count - 1; i++)
                        {
                            var rng = oSheet.Range("B16:AK16");
                            rng.InsertRowsBelow(6);
                        }

                        int Fila = 17;

                        for (int i = 1; i <= IdentifAvisos.Count - 1; i++)
                        {
                            oSheet.Cell(Fila, 2).Value = xlSourceRange;

                            Fila = Fila + 6;
                        }


                        ////// CUENTO OCURRENCIAS X AVISO PARA INSERTAR LAS LINEAS RESEPECIIVAS /////

                        int[] FilasProducto = new int[IdentifAvisos.Count];

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            for (int diaMes = 1; diaMes <= DiasEnMes - 1; diaMes++)
                            {
                                ocurrencias = 0;

                                for (int k = 0; k <= miDetalle.Count - 1; k++)
                                {
                                    if (miDetalle[k].IdentifAviso == IdentifAvisos[i] && miDetalle[k].Fecha.Day == diaMes && miDetalle[k].Fecha.Month == mes)
                                    {
                                        ocurrencias++;
                                    }

                                }

                                if (ocurrencias > 0)
                                {
                                    if (ocurrencias > FilasProducto[i])
                                    {
                                        FilasProducto[i] = ocurrencias;
                                    }
                                }


                            }
                        }

                        //inserta filas en cada uno de los productos de acuerdo a lo que hay en filasproducto
                        Fila = 20;

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            var rng = oSheet.Range("B" + Fila.ToString() + ":AK" + Fila.ToString());

                            rng.InsertRowsBelow(FilasProducto[i] - 1);

                            Fila += 6 + Convert.ToInt32(FilasProducto[i] - 1);
                        }

                        ////// comienzo a rellenar con valores //

                        Fila = 17;

                        for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                        {
                            AvisosDTO aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[j].ToString()));

                            oSheet.Cell(Fila, 3).Value = aviso.EtiquetaProd;

                            Fila += 6 + FilasProducto[j] - 1;
                        }


                        Fila = 20;
                        int FilaPosicional = 20;

                        string[] Celdas = { "", "", "", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG" };

                        miDetalle = miDetalle.OrderBy(p => p.Dia).ThenBy(q => q.Hora).ThenBy(r => r.Salida).ToList();

                        for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                        {
                            for (int k = 1; k <= DiasEnMes; k++)
                            {

                                oSheet.Column(k + 2).Width = 3;

                                for (int l = 0; l <= miDetalle.Count - 1; l++)
                                {

                                    if (miDetalle[l].Fecha.Day == k &&
                                        miDetalle[l].Fecha.Month == mes &&
                                        miDetalle[l].IdentifAviso == IdentifAvisos[j])
                                    {
                                        oSheet.Cell(Fila, k + 2).Value = 1;

                                        int sumDesde = FilaPosicional;
                                        int sumHasta = FilaPosicional + FilasProducto[j] - 1;

                                        string Formula = string.Format("=+SUM({0}{1}:{2}{3})", Celdas[k + 2].ToString(), sumDesde.ToString(), Celdas[k + 2].ToString(), sumHasta.ToString());

                                        oSheet.Cell(FilaPosicional + FilasProducto[j], k + 2).FormulaA1 = Formula;

                                        Fila++;
                                    }

                                }

                                Fila = FilaPosicional;
                            }

                            FilaPosicional = Fila += 6 + FilasProducto[j] - 1;

                        }


                        //// SUBTOTALES DE CADA COLUMNA /////

                        int[] STP = new int[DiasEnMes + 1];
                        int[] STT = new int[DiasEnMes + 1];

                        FilaPosicional = 15;

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            FilaPosicional = FilaPosicional + 5 + FilasProducto[i];

                            for (int j = 1; j <= DiasEnMes; j++)
                            {
                                if (oSheet.Cell(FilaPosicional, j + 2).Value.ToString() == "")
                                {
                                    STP[j] = Convert.ToInt32(oSheet.Cell(FilaPosicional, j + 2).Value + "0");
                                }
                                else
                                {
                                    STP[j] = Convert.ToInt32(oSheet.Cell(FilaPosicional, j + 2).Value);
                                }

                                STT[j] += STP[j];
                            }
                        }

                        FilaPosicional += 2;

                        for (int j = 1; j <= DiasEnMes; j++)
                        {
                            oSheet.Cell(FilaPosicional, j + 2).Value = STT[j];
                        }

                        ////// LLENO MARGEN DERECHO CON TOTALES ////////////

                        FilaPosicional = 15;

                        decimal CostoTotal = 0;
                        decimal GrandTotal = 0;
                        int UnidadesTotales = 0;

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            FilaPosicional = FilaPosicional + 5;

                            for (int j = 0; j <= FilasProducto[i] - 1; j++)
                            {
                                oSheet.Cell("AH" + FilaPosicional.ToString()).FormulaA1 = string.Format("=SUM({0}{1}:{2}{3})", "C", FilaPosicional, "AG", FilaPosicional);

                                for (int k = 0; k <= miDetalle.Count - 1; k++)
                                {
                                    if (miDetalle[k].IdentifAviso == IdentifAvisos[i])
                                    {
                                        oSheet.Cell("AI" + FilaPosicional.ToString()).Value = miDetalle[k].CostoOp;
                                        oSheet.Cell("AJ" + FilaPosicional.ToString()).Value = miDetalle[k].Duracion;
                                        oSheet.Cell("AK" + FilaPosicional.ToString()).Value = Convert.ToDecimal(oSheet.Cell("AH" + FilaPosicional.ToString()).Value) * Convert.ToDecimal(oSheet.Cell("AI" + FilaPosicional.ToString()).Value);

                                        CostoTotal += Convert.ToDecimal(oSheet.Cell("AK" + FilaPosicional.ToString()).Value);

                                        break;
                                    }
                                }

                                oSheet.Cell("AK" + FilaPosicional.ToString()).Value = Convert.ToDecimal(oSheet.Cell("AH" + FilaPosicional.ToString()).Value) * Convert.ToDecimal(oSheet.Cell("AI" + FilaPosicional.ToString()).Value);

                                FilaPosicional++;

                            }

                            oSheet.Cell("AH" + FilaPosicional.ToString()).FormulaA1 = string.Format("=SUM({0}{1}:{2}{3})", "C", FilaPosicional, "AG", FilaPosicional);
                            oSheet.Cell("AI" + FilaPosicional.ToString()).Value = "";
                            oSheet.Cell("AJ" + FilaPosicional.ToString()).Value = "";
                            oSheet.Cell("AK" + FilaPosicional.ToString()).Value = CostoTotal;

                            GrandTotal += CostoTotal;

                            UnidadesTotales += Convert.ToInt32(oSheet.Cell("AH" + FilaPosicional.ToString()).Value);

                            CostoTotal = 0;

                        }

                        FilaPosicional += 2;

                        oSheet.Cell("AH" + FilaPosicional.ToString()).Value = UnidadesTotales;
                        oSheet.Cell("AK" + FilaPosicional.ToString()).Value = GrandTotal;

                        FilaPosicional += 3;

                        oSheet.Cell("AI" + FilaPosicional.ToString()).Value = _Espacio.Responsable;


                        DAO.SetUpDAO STUP = new DAO.SetUpDAO();

                        SetUpDTO setup = STUP.Read(1);

                        oSheet.Cell("AI" + (FilaPosicional + 1).ToString()).Value = setup.Sector;

                        EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);

                        oSheet.Cell("AI" + (FilaPosicional + 2).ToString()).Value = empresa.Name;

                        ////////////////////////////////////////////////////

                        break;

                    }
                case "CERTIFICADO":
                    {
                        CertificadoCabDTO miCabecera = (CertificadoCabDTO)_Cabecera;
                        List<CertificadoDetDTO> miDetalle = (List<CertificadoDetDTO>)_Detalle;
                        miDetalle = miDetalle.OrderBy(P => P.Dia).ThenBy(Q => Q.Hora).ThenBy(R => R.Salida).ToList();
                        int DiaDelAnio = miDetalle[0].Fecha.DayOfYear;
                        string aniomes = miCabecera.AnoMes.ToString();
                        int mes = Convert.ToInt32(aniomes.Substring(4, 2));
                        int anio = Convert.ToInt32(aniomes.Substring(0, 4));
                        DiasEnMes = System.DateTime.DaysInMonth(anio, mes);
                        DiasPautados = new int[DiasEnMes + 1];
                        int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                        int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);
                        int dia = PrimerDiaMes - PrimerDiaSemana + 2;

                        iDia = PrimerDiaSemana;

                        for (int x = 1; x <= DiasEnMes; x++)
                        {
                            for (int j = 0; j <= miDetalle.Count - 1; j++)
                            {
                                if (miDetalle[j].Fecha.Day == x)
                                {
                                    DiasPautados[x]++;
                                }
                            }
                        }

                        iDia = PrimerDiaSemana;

                        //CALCULA LA MAXIMA CANTIDAD DE SALIDAS DE AVISOS
                        MaxLines = 0;

                        for (int k = 0; k <= DiasPautados.Length - 1; k++)
                        {
                            if (DiasPautados[k] > MaxLines)
                            {
                                MaxLines = DiasPautados[k];
                            }
                        }



                        IdentifAvisos.Add(miDetalle[0].IdentifAviso);

                        bool lencontrado = false;

                        for (int i = 0; i <= miDetalle.Count - 1; i++)
                        {
                            lencontrado = false;

                            for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                            {
                                if (IdentifAvisos[j] == miDetalle[i].IdentifAviso)
                                {
                                    lencontrado = true;

                                    break;

                                }
                            }

                            if (!lencontrado)
                            {
                                IdentifAvisos.Add(miDetalle[i].IdentifAviso);

                            }
                        }


                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {

                            int cantsal = 0;

                            for (int j = 0; j <= miDetalle.Count - 1; j++)
                            {
                                if (miDetalle[j].IdentifAviso == IdentifAvisos[i])
                                {

                                    int ThisDay = (int)miDetalle[j].Dia;
                                    ocurrencias = 0;

                                    for (int k = 0; k <= miDetalle.Count - 1; k++)
                                    {
                                        if ((int)miDetalle[k].Dia == ThisDay && miDetalle[k].IdentifAviso == IdentifAvisos[i])
                                        {
                                            ocurrencias++;
                                        }
                                    }

                                    cantsal++;
                                }
                            }
                        }


                        //LIMPIEZA DE DIAS Y FECHAS
                        for (int i = 1; i <= 31; i++)
                        {
                            oSheet.Cell(18, 2 + i).Value = "";
                            oSheet.Cell(19, 2 + i).Value = "";
                        }

                        for (int i = 1; i <= (DiasEnMes); i++)
                        {
                            oSheet.Cell(18, 2 + i).Value = DiasSemana[iDia].ToUpper();
                            oSheet.Cell(19, 2 + i).Value = i;

                            iDia++;

                            if (iDia == 8)
                            {
                                iDia = 1;
                            }
                        }
                        /// FIN ARMADO CALENDARIO ///
                        /// 

                        /////////////////
                        //EMPIEZO A ARMAR FRAME PARA CADA UNO DE LOS PRODUCTOS

                        var xlSourceRange = oSheet.Range("B17:AK22");


                        for (int i = 1; i <= IdentifAvisos.Count - 1; i++)
                        {
                            var rng = oSheet.Range("B16:AK16");
                            rng.InsertRowsBelow(6);
                        }

                        int Fila = 17;

                        for (int i = 1; i <= IdentifAvisos.Count - 1; i++)
                        {
                            oSheet.Cell(Fila, 2).Value = xlSourceRange;

                            Fila = Fila + 6;
                        }


                        ////// CUENTO OCURRENCIAS X AVISO PARA INSERTAR LAS LINEAS RESEPECIIVAS /////

                        int[] FilasProducto = new int[IdentifAvisos.Count];

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            for (int diaMes = 1; diaMes <= DiasEnMes - 1; diaMes++)
                            {
                                ocurrencias = 0;

                                for (int k = 0; k <= miDetalle.Count - 1; k++)
                                {
                                    if (miDetalle[k].IdentifAviso == IdentifAvisos[i] && miDetalle[k].Fecha.Day == diaMes && miDetalle[k].Fecha.Month == mes)
                                    {
                                        ocurrencias++;
                                    }

                                }

                                if (ocurrencias > 0)
                                {
                                    if (ocurrencias > FilasProducto[i])
                                    {
                                        FilasProducto[i] = ocurrencias;
                                    }
                                }


                            }
                        }

                        //inserta filas en cada uno de los productos de acuerdo a lo que hay en filasproducto
                        Fila = 20;

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            var rng = oSheet.Range("B" + Fila.ToString() + ":AK" + Fila.ToString());

                            rng.InsertRowsBelow(FilasProducto[i] - 1);

                            Fila += 6 + Convert.ToInt32(FilasProducto[i] - 1);
                        }

                        ////// comienzo a rellenar con valores //

                        Fila = 17;

                        for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                        {
                            AvisosDTO aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[j].ToString()));

                            oSheet.Cell(Fila, 3).Value = aviso.EtiquetaProd;

                            Fila += 6 + FilasProducto[j] - 1;
                        }


                        Fila = 20;
                        int FilaPosicional = 20;

                        string[] Celdas = { "", "", "", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG" };

                        miDetalle = miDetalle.OrderBy(p => p.Dia).ThenBy(q => q.Hora).ThenBy(r => r.Salida).ToList();

                        for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                        {
                            for (int k = 1; k <= DiasEnMes; k++)
                            {

                                oSheet.Column(k + 2).Width = 3;

                                for (int l = 0; l <= miDetalle.Count - 1; l++)
                                {

                                    if (miDetalle[l].Fecha.Day == k &&
                                        miDetalle[l].Fecha.Month == mes &&
                                        miDetalle[l].IdentifAviso == IdentifAvisos[j])
                                    {
                                        oSheet.Cell(Fila, k + 2).Value = 1;

                                        int sumDesde = FilaPosicional;
                                        int sumHasta = FilaPosicional + FilasProducto[j] - 1;

                                        string Formula = string.Format("=+SUM({0}{1}:{2}{3})", Celdas[k + 2].ToString(), sumDesde.ToString(), Celdas[k + 2].ToString(), sumHasta.ToString());

                                        oSheet.Cell(FilaPosicional + FilasProducto[j], k + 2).FormulaA1 = Formula;

                                        Fila++;
                                    }

                                }

                                Fila = FilaPosicional;
                            }

                            FilaPosicional = Fila += 6 + FilasProducto[j] - 1;

                        }


                        //// SUBTOTALES DE CADA COLUMNA /////

                        int[] STP = new int[DiasEnMes + 1];
                        int[] STT = new int[DiasEnMes + 1];

                        FilaPosicional = 15;

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            FilaPosicional = FilaPosicional + 5 + FilasProducto[i];

                            for (int j = 1; j <= DiasEnMes; j++)
                            {
                                if (oSheet.Cell(FilaPosicional, j + 2).Value.ToString() == "")
                                {
                                    STP[j] = Convert.ToInt32(oSheet.Cell(FilaPosicional, j + 2).Value + "0");
                                }
                                else
                                {
                                    STP[j] = Convert.ToInt32(oSheet.Cell(FilaPosicional, j + 2).Value);
                                }

                                STT[j] += STP[j];
                            }
                        }

                        FilaPosicional += 2;

                        for (int j = 1; j <= DiasEnMes; j++)
                        {
                            oSheet.Cell(FilaPosicional, j + 2).Value = STT[j];
                        }

                        ////// LLENO MARGEN DERECHO CON TOTALES ////////////

                        FilaPosicional = 15;

                        decimal CostoTotal = 0;
                        decimal GrandTotal = 0;
                        int UnidadesTotales = 0;

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            FilaPosicional = FilaPosicional + 5;

                            for (int j = 0; j <= FilasProducto[i] - 1; j++)
                            {
                                oSheet.Cell("AH" + FilaPosicional.ToString()).FormulaA1 = string.Format("=SUM({0}{1}:{2}{3})", "C", FilaPosicional, "AG", FilaPosicional);

                                for (int k = 0; k <= miDetalle.Count - 1; k++)
                                {
                                    if (miDetalle[k].IdentifAviso == IdentifAvisos[i])
                                    {
                                        oSheet.Cell("AI" + FilaPosicional.ToString()).Value = miDetalle[k].CostoOp;
                                        oSheet.Cell("AJ" + FilaPosicional.ToString()).Value = miDetalle[k].Duracion;
                                        oSheet.Cell("AK" + FilaPosicional.ToString()).Value = Convert.ToDecimal(oSheet.Cell("AH" + FilaPosicional.ToString()).Value) * Convert.ToDecimal(oSheet.Cell("AI" + FilaPosicional.ToString()).Value);

                                        CostoTotal += Convert.ToDecimal(oSheet.Cell("AK" + FilaPosicional.ToString()).Value);

                                        break;
                                    }
                                }

                                oSheet.Cell("AK" + FilaPosicional.ToString()).Value = Convert.ToDecimal(oSheet.Cell("AH" + FilaPosicional.ToString()).Value) * Convert.ToDecimal(oSheet.Cell("AI" + FilaPosicional.ToString()).Value);

                                FilaPosicional++;

                            }

                            oSheet.Cell("AH" + FilaPosicional.ToString()).FormulaA1 = string.Format("=SUM({0}{1}:{2}{3})", "C", FilaPosicional, "AG", FilaPosicional);
                            oSheet.Cell("AI" + FilaPosicional.ToString()).Value = "";
                            oSheet.Cell("AJ" + FilaPosicional.ToString()).Value = "";
                            oSheet.Cell("AK" + FilaPosicional.ToString()).Value = CostoTotal;

                            GrandTotal += CostoTotal;

                            UnidadesTotales += Convert.ToInt32(oSheet.Cell("AH" + FilaPosicional.ToString()).Value);

                            CostoTotal = 0;

                        }

                        FilaPosicional += 2;

                        oSheet.Cell("AH" + FilaPosicional.ToString()).Value = UnidadesTotales;
                        oSheet.Cell("AK" + FilaPosicional.ToString()).Value = GrandTotal;

                        FilaPosicional += 3;

                        oSheet.Cell("AI" + FilaPosicional.ToString()).Value = _Espacio.Responsable;


                        DAO.SetUpDAO STUP = new DAO.SetUpDAO();

                        SetUpDTO setup = STUP.Read(1);

                        oSheet.Cell("AI" + (FilaPosicional + 1).ToString()).Value = setup.Sector;

                        EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);

                        oSheet.Cell("AI" + (FilaPosicional + 2).ToString()).Value = empresa.Name;

                        ////////////////////////////////////////////////////

                        break;
                    }

            }

            /////////////////

            oWB.SaveAs(nomArchivo);
            oWB.Dispose();
            oSheet = null;
            oWB = null;
            GC.Collect();
        }
        public void Detalle_OP_PNT_Salida(string nomarchivo)
        {

            ////// ClosedXML ////////
            XLWorkbook oWB = new XLWorkbook(nomarchivo);
            var oSheet = oWB.Worksheet(1);

            int Espaciado = 4;

            switch (_Estado.ToUpper())
            {
                #region Ordenado
                case "ORDENADO": {

                    AvisosDTO aviso = null;
                    OrdenadoCabDTO miCabecera = (OrdenadoCabDTO)_Cabecera;
                    List<OrdenadoDetDTO> miDetalle = (List<OrdenadoDetDTO>)_Detalle;
                    miDetalle = miDetalle.OrderBy(p =>p.Dia).ThenBy(q =>q.Hora).ThenBy(r =>r.Salida).ToList();

                    string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };

                    //ARMADO DE CALENDARIO - MEJORAR
                    string aniomes = miCabecera.AnoMes.ToString();
                    int mes = Convert.ToInt32(aniomes.Substring(4, 2));
                    int anio = Convert.ToInt32(aniomes.Substring(0, 4));
                    int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);
                    string[] DiasSemana = { "", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };
                    int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                    int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);
                    int dia = PrimerDiaMes - PrimerDiaSemana + 2;
                    int DiaDelAnio = miDetalle[0].Fecha.DayOfYear;
                    int[] DiasPautados = new int[DiasEnMes + 1];

                    for (int x = 1; x <= DiasEnMes; x++)
                    {
                        for (int j = 0; j <= miDetalle.Count - 1; j++)
                        {
                            if (miDetalle[j].Fecha.Day == x)
                            {
                                DiasPautados[x]++;
                            }
                        }
                    }

                    //CALCULA LA MAXIMA CANTIDAD DE SALIDAS DE AVISOS
                    int MaxLines = 0;

                    for (int k = 0; k <= DiasPautados.Length - 1; k++)
                    {
                        if (DiasPautados[k] > MaxLines)
                        {
                            MaxLines = DiasPautados[k];
                        }
                    }

                    string[] Celdas = { "", "", "", "C", "D", "E", "F", "G", "H", "I" };

                    ////// inicio de semanas ///////////

                    int Salida = 0;
                    int _Fila = 21;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila).ToString() + ":N" + (_Fila).ToString());

                        rng.InsertRowsBelow(MaxLines-1);

                        for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                        {
                            Salida++;

                            oSheet.Cell("A" + (i)).Value = "SALIDA " + Salida.ToString();
                        }
                    }
                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {
                        string aa = oSheet.Cell(20, Columnas).Value.ToString();
                        string bb = Convert.ToDateTime(aa).Day.ToString();


                        List<OrdenadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == aa.Substring(3,2)).ToList();

                        if (SubLista.Count > 0)
                        {
                            for (int i = 0; i <= SubLista.Count - 1; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i].IdentifAviso));

                                if (oSheet.Cell(20 + i, 2).Value == null || oSheet.Cell(25 + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(21 + i, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(21 + i, Columnas).Value = aviso.EtiquetaProd;
                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(20 + MaxLines + 1, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (21).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), 20 + SubLista.Count);
                            }
                            else
                            {
                                oSheet.Cell(20 + MaxLines + 1, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (21).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }

                    ////// SEMANA 2 //////

                    Salida = 0;
                    _Fila = 21 + MaxLines -1 + Espaciado;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila + 1).ToString() + ":N" + (_Fila + 1).ToString());

                        rng.InsertRowsBelow(MaxLines - 1);

                        for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                        {
                            Salida++;

                            oSheet.Cell("A" + (i +1)).Value = "SALIDA " + Salida.ToString();
                        }
                    }
                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {
                        string aa = oSheet.Cell(20 + MaxLines + 4, Columnas).Value.ToString();

                        string bb = Convert.ToDateTime(aa).Day.ToString();

                        List<OrdenadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == aa.Substring(3, 2)).ToList();

                        if (SubLista.Count > 0)
                        {
                            for (int i = 1; i <= SubLista.Count; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i-1].IdentifAviso));

                                if (oSheet.Cell(_Fila + i, 2).Value == null || oSheet.Cell(_Fila + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(_Fila + i, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(_Fila + i, Columnas).Value = aviso.EtiquetaProd;

                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(_Fila + MaxLines + 1, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (_Fila + 1).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), _Fila + MaxLines);
                            }
                            else
                            {
                                oSheet.Cell(_Fila + SubLista.Count + 1, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (_Fila + 1).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }


                    //////////////////////

                    ////// SEMANA 3//////

                    Salida = 0;
                    _Fila += MaxLines + Espaciado;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila + 1).ToString() + ":N" + (_Fila + 1).ToString());
                        rng.InsertRowsBelow(MaxLines - 1);
                    }

                    _Fila++;

                    for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                    {
                        Salida++;

                        oSheet.Cell("A" + (i)).Value = "SALIDA " + Salida.ToString();
                    }

                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {
                        string aa = oSheet.Cell(20 + MaxLines + 4, Columnas).Value.ToString();

                        string bb = Convert.ToDateTime(aa).Day.ToString();

                        List<OrdenadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == aa.Substring(3, 2)).ToList();

                        if (SubLista.Count > 0)
                        {
                            for (int i = 1; i <= SubLista.Count; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i - 1].IdentifAviso));

                                if (oSheet.Cell(_Fila + i -1, 2).Value == null || oSheet.Cell(_Fila + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(_Fila + i -1, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(_Fila + i -1, Columnas).Value = aviso.EtiquetaProd;

                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (_Fila).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), _Fila + MaxLines -1);
                            }
                            else
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (_Fila).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }


                    //////////////////////

                    ////// SEMANA 4//////

                    Salida = 0;
                    _Fila += MaxLines + Espaciado -1;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila + 1).ToString() + ":N" + (_Fila + 1).ToString());
                        rng.InsertRowsBelow(MaxLines - 1);
                    }

                    _Fila++;

                    for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                    {
                        Salida++;

                        oSheet.Cell("A" + (i)).Value = "SALIDA " + Salida.ToString();
                    }

                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {
                        string aa = oSheet.Cell(_Fila -1, Columnas).Value.ToString();

                        string bb = Convert.ToDateTime(aa).Day.ToString();

                        List<OrdenadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == aa.Substring(3, 2)).ToList();

                        if (SubLista.Count > 0)
                        {
                            for (int i = 1; i <= SubLista.Count; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i - 1].IdentifAviso));

                                if (oSheet.Cell(_Fila + i - 1, 2).Value == null || oSheet.Cell(_Fila + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(_Fila + i - 1, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(_Fila + i - 1, Columnas).Value = aviso.EtiquetaProd;

                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (_Fila).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), _Fila + MaxLines - 1);
                            }
                            else
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (_Fila).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }


                    //////////////////////

                    ////// SEMANA 5//////

                    Salida = 0;
                    _Fila += MaxLines + Espaciado -1;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila + 1).ToString() + ":N" + (_Fila + 1).ToString());
                        rng.InsertRowsBelow(MaxLines - 1);
                    }

                    _Fila++;

                    for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                    {
                        Salida++;

                        oSheet.Cell("A" + (i)).Value = "SALIDA " + Salida.ToString();
                    }

                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {
                        string aa = oSheet.Cell(_Fila -1, Columnas).Value.ToString();

                        string bb = Convert.ToDateTime(aa).Day.ToString();

                        List<OrdenadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == aa.Substring(3, 2)).ToList();

                        if (SubLista.Count > 0)
                        {
                            for (int i = 1; i <= SubLista.Count; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i - 1].IdentifAviso));

                                if (oSheet.Cell(_Fila + i - 1, 2).Value == null || oSheet.Cell(_Fila + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(_Fila + i - 1, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(_Fila + i - 1, Columnas).Value = aviso.EtiquetaProd;

                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (_Fila).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), _Fila + MaxLines - 1);
                            }
                            else
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (_Fila).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }

                    ///////////// fin de semanas //////////////

                    int Columna = 6; //COD. INGESTA
                    int Fila = 5;

                    while (1 == 1)
                    {
                        if (oSheet.Cell(Fila, Columna).Value != null && oSheet.Cell(Fila, Columna).Value.ToString() == "COD. INGESTA")
                        {

                            List<string> IdentifAvisos = new List<string>();

                            for (int i = 0; i <= miDetalle.Count - 1; i++)
                            {

                                if (IdentifAvisos.Count == 0)
                                {
                                    IdentifAvisos.Add(miDetalle[i].IdentifAviso);
                                }

                                bool lencontrado = false;

                                string scadena = miDetalle[i].IdentifAviso;

                                for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                                {
                                    if (IdentifAvisos[j] == scadena)
                                    {
                                        lencontrado = true;

                                        break;
                                    }
                                }

                                if (!lencontrado)
                                {
                                    IdentifAvisos.Add(miDetalle[i].IdentifAviso);

                                    break;
                                }

                            }

                            for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                            {

                                Fila++;

                                Columna = 3;

                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[i]));
                                oSheet.Cell(Fila, Columna).Value = aviso.EtiquetaProd;

                                DTO.PiezasArteDTO pieza = CRUDHelper.Read(string.Format("IdentifPieza = '{0}'", aviso.IdentifPieza),
                                                          BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.PiezasArte));

                                DTO.AnunInternosDTO ai = CRUDHelper.Read(string.Format("IdentifAnun = '{0}'", pieza.IdentifAnun),
                                                              BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AnunInternos));

                                oSheet.Cell(Fila, Columna + 1).Value = ai.Name;
                                oSheet.Cell(Fila, Columna + 2).Value = aviso.Zocalo;
                                oSheet.Cell(Fila, Columna + 3).Value = aviso.NroIngesta;

                                int cantsal = 0;

                                for (int j = 0; j <= miDetalle.Count - 1; j++)
                                {
                                    if (miDetalle[j].IdentifAviso == IdentifAvisos[i])
                                    {
                                        cantsal++;
                                    }
                                }

                                oSheet.Cell(Fila, Columna + 4).Value = cantsal;

                                Columna = 9;

                                decimal CostoPorSalida = miDetalle[0].CostoOp / miDetalle.Count;
                                oSheet.Cell(Fila, Columna).Value = CostoPorSalida;


                            }

                            Fila += 7;

                            oSheet.Cell(Fila, Columna).Value = _Espacio.Responsable;

                            Fila++;

                            DAO.SetUpDAO STUP = new DAO.SetUpDAO();

                            SetUpDTO setup = STUP.Read(1);

                            string sector = setup.Sector;

                            oSheet.Cell(Fila, Columna).Value = sector;

                            Fila++;

                            EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);

                            oSheet.Cell(Fila, Columna).Value = empresa.Name;

                            // telefonos //

                            for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                            {
                                AvisosIdAtenDTO aia = CRUDHelper.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[i]), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AvisosIdAten));
                                oSheet.Cell("E" + (Fila + i).ToString()).Value = "'" + aia.IdentifIdentAte;


                            }
                            //////////////


                            break;
                        }

                        Fila++;
                    }

                   
                    break;
                }
                #endregion

                #region Estimado
                case "ESTIMADO": {

                    AvisosDTO aviso = null;
                    EstimadoCabDTO miCabecera = (EstimadoCabDTO)_Cabecera;
                    List<EstimadoDetDTO> miDetalle = (List<EstimadoDetDTO>)_Detalle;
                    miDetalle = miDetalle.OrderBy(p => p.Dia).ThenBy(q => q.Hora).ThenBy(r => r.Salida).ToList();

                    string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };

                    //ARMADO DE CALENDARIO - MEJORAR
                    string aniomes = miCabecera.AnoMes.ToString();
                    int mes = Convert.ToInt32(aniomes.Substring(4, 2));
                    int anio = Convert.ToInt32(aniomes.Substring(0, 4));
                    int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);
                    string[] DiasSemana = { "", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };
                    int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                    int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);
                    int dia = PrimerDiaMes - PrimerDiaSemana + 2;
                    int DiaDelAnio = miDetalle[0].Fecha.DayOfYear;
                    int[] DiasPautados = new int[DiasEnMes + 1];

                    for (int x = 1; x <= DiasEnMes; x++)
                    {
                        for (int j = 0; j <= miDetalle.Count - 1; j++)
                        {
                            if (miDetalle[j].Fecha.Day == x)
                            {
                                DiasPautados[x]++;
                            }
                        }
                    }

                    //CALCULA LA MAXIMA CANTIDAD DE SALIDAS DE AVISOS
                    int MaxLines = 0;

                    for (int k = 0; k <= DiasPautados.Length - 1; k++)
                    {
                        if (DiasPautados[k] > MaxLines)
                        {
                            MaxLines = DiasPautados[k];
                        }
                    }

                    string[] Celdas = { "", "", "", "C", "D", "E", "F", "G", "H", "I" };

                    ////// inicio de semanas ///////////

                    int Salida = 0;
                    int _Fila = 21;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila).ToString() + ":N" + (_Fila).ToString());

                        rng.InsertRowsBelow(MaxLines - 1);

                        for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                        {
                            Salida++;

                            oSheet.Cell("A" + (i)).Value = "SALIDA " + Salida.ToString();
                        }
                    }
                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {
                        string aa = oSheet.Cell(20, Columnas).Value.ToString();

                        DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays( Convert.ToInt32(aa) - 2);

                        //string bb = Convert.ToDateTime(aa).Day.ToString();
                        string bb = theDate.Day.ToString();

                        List<EstimadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == theDate.ToString().Substring(3, 2)).ToList();

                        if (SubLista.Count > 0)
                        {
                            for (int i = 0; i <= SubLista.Count - 1; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i].IdentifAviso));

                                if (oSheet.Cell(20 + i, 2).Value == null || oSheet.Cell(25 + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(21 + i, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(21 + i, Columnas).Value = aviso.EtiquetaProd;
                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(20 + MaxLines + 1, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (21).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), 20 + SubLista.Count);
                            }
                            else
                            {
                                oSheet.Cell(20 + MaxLines + 1, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (21).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }

                    ////// SEMANA 2 //////

                    Salida = 0;

                    _Fila = 21 + MaxLines - 1 + Espaciado;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila + 1).ToString() + ":N" + (_Fila + 1).ToString());

                        rng.InsertRowsBelow(MaxLines - 1);

                        for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                        {
                            Salida++;

                            oSheet.Cell("A" + (i + 1)).Value = "SALIDA " + Salida.ToString();
                        }
                    }
                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {
                        string aa = oSheet.Cell(20 + MaxLines + 4, Columnas).Value.ToString();

                        DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 2);
                        string bb = theDate.Day.ToString();
                        List<EstimadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == theDate.ToString().Substring(3, 2)).ToList();

                        //string aa = oSheet.Cell(20 + MaxLines + 4, Columnas).Value.ToString();

                        //DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 1);

                        ////string bb = Convert.ToDateTime(aa).Day.ToString();
                        //string bb = theDate.Day.ToString();

                        //List<EstimadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString() == theDate.ToString().Substring(3, 2)).ToList();


                        if (SubLista.Count > 0)
                        {
                            for (int i = 1; i <= SubLista.Count; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i - 1].IdentifAviso));

                                if (oSheet.Cell(_Fila + i, 2).Value == null || oSheet.Cell(_Fila + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(_Fila + i, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(_Fila + i, Columnas).Value = aviso.EtiquetaProd;

                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(_Fila + MaxLines + 1, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (_Fila + 1).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), _Fila + MaxLines);
                            }
                            else
                            {
                                oSheet.Cell(_Fila + SubLista.Count + 1, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (_Fila + 1).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }


                    //////////////////////

                    ////// SEMANA 3//////

                    Salida = 0;
                    _Fila += MaxLines + Espaciado;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila + 1).ToString() + ":N" + (_Fila + 1).ToString());
                        rng.InsertRowsBelow(MaxLines - 1);
                    }

                    _Fila++;

                    for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                    {
                        Salida++;

                        oSheet.Cell("A" + (i)).Value = "SALIDA " + Salida.ToString();
                    }

                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {
                        string aa = oSheet.Cell(_Fila - 1, Columnas).Value.ToString();
                        DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 2);
                        string bb = theDate.Day.ToString();
                        List<EstimadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == theDate.ToString().Substring(3, 2)).ToList();

                        //string aa = oSheet.Cell(20 + MaxLines + 4, Columnas).Value.ToString();
                        //DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 1);
                        //string bb = theDate.Day.ToString();
                        //List<EstimadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString() == theDate.ToString().Substring(3, 2)).ToList();


                        if (SubLista.Count > 0)
                        {
                            for (int i = 1; i <= SubLista.Count; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i - 1].IdentifAviso));

                                if (oSheet.Cell(_Fila + i - 1, 2).Value == null || oSheet.Cell(_Fila + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(_Fila + i - 1, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(_Fila + i - 1, Columnas).Value = aviso.EtiquetaProd;

                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (_Fila).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), _Fila + MaxLines - 1);
                            }
                            else
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (_Fila).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }


                    //////////////////////

                    ////// SEMANA 4//////

                    Salida = 0;
                    _Fila += MaxLines + Espaciado - 1;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila + 1).ToString() + ":N" + (_Fila + 1).ToString());
                        rng.InsertRowsBelow(MaxLines - 1);
                    }

                    _Fila++;

                    for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                    {
                        Salida++;

                        oSheet.Cell("A" + (i)).Value = "SALIDA " + Salida.ToString();
                    }

                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {

                        string aa = oSheet.Cell(_Fila - 1, Columnas).Value.ToString();
                        DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 2);
                        string bb = theDate.Day.ToString();
                        List<EstimadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == theDate.ToString().Substring(3, 2)).ToList();

                        if (SubLista.Count > 0)
                        {
                            for (int i = 1; i <= SubLista.Count; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i - 1].IdentifAviso));

                                if (oSheet.Cell(_Fila + i - 1, 2).Value == null || oSheet.Cell(_Fila + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(_Fila + i - 1, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(_Fila + i - 1, Columnas).Value = aviso.EtiquetaProd;

                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (_Fila).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), _Fila + MaxLines - 1);
                            }
                            else
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (_Fila).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }


                    //////////////////////

                    ////// SEMANA 5//////

                    Salida = 0;
                    _Fila += MaxLines + Espaciado - 1;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila + 1).ToString() + ":N" + (_Fila + 1).ToString());
                        rng.InsertRowsBelow(MaxLines - 1);
                    }

                    _Fila++;

                    for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                    {
                        Salida++;

                        oSheet.Cell("A" + (i)).Value = "SALIDA " + Salida.ToString();
                    }

                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {

                        string aa = oSheet.Cell(_Fila - 1, Columnas).Value.ToString();
                        DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 2);
                        string bb = theDate.Day.ToString();
                        List<EstimadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == theDate.ToString().Substring(3, 2)).ToList();

                        if (SubLista.Count > 0)
                        {
                            for (int i = 1; i <= SubLista.Count; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i - 1].IdentifAviso));

                                if (oSheet.Cell(_Fila + i - 1, 2).Value == null || oSheet.Cell(_Fila + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(_Fila + i - 1, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(_Fila + i - 1, Columnas).Value = aviso.EtiquetaProd;

                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (_Fila).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), _Fila + MaxLines - 1);
                            }
                            else
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (_Fila).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }

                    ///////////// fin de semanas //////////////

                    int Columna = 6; //COD. INGESTA
                    int Fila = 5;

                    while (1 == 1)
                    {
                        if (oSheet.Cell(Fila, Columna).Value != null && oSheet.Cell(Fila, Columna).Value.ToString() == "COD. INGESTA")
                        {

                            List<string> IdentifAvisos = new List<string>();

                            for (int i = 0; i <= miDetalle.Count - 1; i++)
                            {

                                if (IdentifAvisos.Count == 0)
                                {
                                    IdentifAvisos.Add(miDetalle[i].IdentifAviso);
                                }

                                bool lencontrado = false;

                                string scadena = miDetalle[i].IdentifAviso;

                                for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                                {
                                    if (IdentifAvisos[j] == scadena)
                                    {
                                        lencontrado = true;

                                        break;
                                    }
                                }

                                if (!lencontrado)
                                {
                                    IdentifAvisos.Add(miDetalle[i].IdentifAviso);

                                    break;
                                }

                            }

                            for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                            {

                                Fila++;

                                Columna = 3;

                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[i]));
                                oSheet.Cell(Fila, Columna).Value = aviso.EtiquetaProd;

                                DTO.PiezasArteDTO pieza = CRUDHelper.Read(string.Format("IdentifPieza = '{0}'", aviso.IdentifPieza),
                                                          BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.PiezasArte));

                                DTO.AnunInternosDTO ai = CRUDHelper.Read(string.Format("IdentifAnun = '{0}'", pieza.IdentifAnun),
                                                              BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AnunInternos));

                                oSheet.Cell(Fila, Columna + 1).Value = ai.Name;
                                oSheet.Cell(Fila, Columna + 2).Value = aviso.Zocalo;
                                oSheet.Cell(Fila, Columna + 3).Value = aviso.NroIngesta;

                                int cantsal = 0;

                                for (int j = 0; j <= miDetalle.Count - 1; j++)
                                {
                                    if (miDetalle[j].IdentifAviso == IdentifAvisos[i])
                                    {
                                        cantsal++;
                                    }
                                }

                                oSheet.Cell(Fila, Columna + 4).Value = cantsal;

                                Columna = 9;

                                decimal CostoPorSalida = miDetalle[0].CostoOp / miDetalle.Count;
                                oSheet.Cell(Fila, Columna).Value = CostoPorSalida;


                            }

                            Fila += 7;

                            oSheet.Cell(Fila, Columna).Value = _Espacio.Responsable;

                            Fila++;

                            DAO.SetUpDAO STUP = new DAO.SetUpDAO();

                            SetUpDTO setup = STUP.Read(1);

                            string sector = setup.Sector;

                            oSheet.Cell(Fila, Columna).Value = sector;

                            Fila++;

                            EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);

                            oSheet.Cell(Fila, Columna).Value = empresa.Name;

                            // telefonos //

                            for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                            {
                                AvisosIdAtenDTO aia = CRUDHelper.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[i]), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AvisosIdAten));
                                oSheet.Cell("E" + (Fila + i).ToString()).Value = "'" + aia.IdentifIdentAte;


                            }
                            //////////////


                            break;
                        }

                        Fila++;
                    }


                    break;
                }
#endregion

                #region Certificado

                case "CERTIFICADO": {

                    AvisosDTO aviso = null;
                    CertificadoCabDTO miCabecera = (CertificadoCabDTO)_Cabecera;
                    List<CertificadoDetDTO> miDetalle = (List<CertificadoDetDTO>)_Detalle;
                    miDetalle = miDetalle.OrderBy(p => p.Dia).ThenBy(q => q.Hora).ThenBy(r => r.Salida).ToList();

                    string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };

                    //ARMADO DE CALENDARIO - MEJORAR
                    string aniomes = miCabecera.AnoMes.ToString();
                    int mes = Convert.ToInt32(aniomes.Substring(4, 2));
                    int anio = Convert.ToInt32(aniomes.Substring(0, 4));
                    int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);
                    string[] DiasSemana = { "", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };
                    int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                    int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);
                    int dia = PrimerDiaMes - PrimerDiaSemana + 2;
                    int DiaDelAnio = miDetalle[0].Fecha.DayOfYear;
                    int[] DiasPautados = new int[DiasEnMes + 1];

                    for (int x = 1; x <= DiasEnMes; x++)
                    {
                        for (int j = 0; j <= miDetalle.Count - 1; j++)
                        {
                            if (miDetalle[j].Fecha.Day == x)
                            {
                                DiasPautados[x]++;
                            }
                        }
                    }

                    //CALCULA LA MAXIMA CANTIDAD DE SALIDAS DE AVISOS
                    int MaxLines = 0;

                    for (int k = 0; k <= DiasPautados.Length - 1; k++)
                    {
                        if (DiasPautados[k] > MaxLines)
                        {
                            MaxLines = DiasPautados[k];
                        }
                    }

                    string[] Celdas = { "", "", "", "C", "D", "E", "F", "G", "H", "I" };

                    ////// inicio de semanas ///////////

                    int Salida = 0;
                    int _Fila = 21;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila).ToString() + ":N" + (_Fila).ToString());

                        rng.InsertRowsBelow(MaxLines - 1);

                        for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                        {
                            Salida++;

                            oSheet.Cell("A" + (i)).Value = "SALIDA " + Salida.ToString();
                        }
                    }
                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {
                        string aa = oSheet.Cell(20, Columnas).Value.ToString();

                        DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 2);

                        //string bb = Convert.ToDateTime(aa).Day.ToString();
                        string bb = theDate.Day.ToString();

                        List<CertificadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == theDate.ToString().Substring(3, 2)).ToList();

                        if (SubLista.Count > 0)
                        {
                            for (int i = 0; i <= SubLista.Count - 1; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i].IdentifAviso));

                                if (oSheet.Cell(20 + i, 2).Value == null || oSheet.Cell(25 + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(21 + i, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(21 + i, Columnas).Value = aviso.EtiquetaProd;
                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(20 + MaxLines + 1, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (21).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), 20 + SubLista.Count);
                            }
                            else
                            {
                                oSheet.Cell(20 + MaxLines + 1, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (21).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }

                    ////// SEMANA 2 //////

                    Salida = 0;

                    _Fila = 21 + MaxLines - 1 + Espaciado;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila + 1).ToString() + ":N" + (_Fila + 1).ToString());

                        rng.InsertRowsBelow(MaxLines - 1);

                        for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                        {
                            Salida++;

                            oSheet.Cell("A" + (i + 1)).Value = "SALIDA " + Salida.ToString();
                        }
                    }
                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {
                        string aa = oSheet.Cell(20 + MaxLines + 4, Columnas).Value.ToString();

                        DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 2);
                        string bb = theDate.Day.ToString();
                        List<CertificadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == theDate.ToString().Substring(3, 2)).ToList();

                        //string aa = oSheet.Cell(20 + MaxLines + 4, Columnas).Value.ToString();

                        //DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 1);

                        ////string bb = Convert.ToDateTime(aa).Day.ToString();
                        //string bb = theDate.Day.ToString();

                        //List<EstimadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString() == theDate.ToString().Substring(3, 2)).ToList();


                        if (SubLista.Count > 0)
                        {
                            for (int i = 1; i <= SubLista.Count; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i - 1].IdentifAviso));

                                if (oSheet.Cell(_Fila + i, 2).Value == null || oSheet.Cell(_Fila + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(_Fila + i, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(_Fila + i, Columnas).Value = aviso.EtiquetaProd;

                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(_Fila + MaxLines + 1, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (_Fila + 1).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), _Fila + MaxLines);
                            }
                            else
                            {
                                oSheet.Cell(_Fila + SubLista.Count + 1, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (_Fila + 1).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }


                    //////////////////////

                    ////// SEMANA 3//////

                    Salida = 0;
                    _Fila += MaxLines + Espaciado;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila + 1).ToString() + ":N" + (_Fila + 1).ToString());
                        rng.InsertRowsBelow(MaxLines - 1);
                    }

                    _Fila++;

                    for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                    {
                        Salida++;

                        oSheet.Cell("A" + (i)).Value = "SALIDA " + Salida.ToString();
                    }

                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {
                        string aa = oSheet.Cell(_Fila - 1, Columnas).Value.ToString();
                        DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 2);
                        string bb = theDate.Day.ToString();
                        List<CertificadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == theDate.ToString().Substring(3, 2)).ToList();

                        //string aa = oSheet.Cell(20 + MaxLines + 4, Columnas).Value.ToString();
                        //DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 1);
                        //string bb = theDate.Day.ToString();
                        //List<EstimadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString() == theDate.ToString().Substring(3, 2)).ToList();


                        if (SubLista.Count > 0)
                        {
                            for (int i = 1; i <= SubLista.Count; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i - 1].IdentifAviso));

                                if (oSheet.Cell(_Fila + i - 1, 2).Value == null || oSheet.Cell(_Fila + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(_Fila + i - 1, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(_Fila + i - 1, Columnas).Value = aviso.EtiquetaProd;

                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (_Fila).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), _Fila + MaxLines - 1);
                            }
                            else
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (_Fila).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }


                    //////////////////////

                    ////// SEMANA 4//////

                    Salida = 0;
                    _Fila += MaxLines + Espaciado - 1;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila + 1).ToString() + ":N" + (_Fila + 1).ToString());
                        rng.InsertRowsBelow(MaxLines - 1);
                    }

                    _Fila++;

                    for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                    {
                        Salida++;

                        oSheet.Cell("A" + (i)).Value = "SALIDA " + Salida.ToString();
                    }

                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {

                        string aa = oSheet.Cell(_Fila - 1, Columnas).Value.ToString();
                        DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 2);
                        string bb = theDate.Day.ToString();
                        List<CertificadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == theDate.ToString().Substring(3, 2)).ToList();

                        if (SubLista.Count > 0)
                        {
                            for (int i = 1; i <= SubLista.Count; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i - 1].IdentifAviso));

                                if (oSheet.Cell(_Fila + i - 1, 2).Value == null || oSheet.Cell(_Fila + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(_Fila + i - 1, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(_Fila + i - 1, Columnas).Value = aviso.EtiquetaProd;

                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (_Fila).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), _Fila + MaxLines - 1);
                            }
                            else
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (_Fila).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }


                    //////////////////////

                    ////// SEMANA 5//////

                    Salida = 0;
                    _Fila += MaxLines + Espaciado - 1;

                    if (MaxLines > 1)
                    {
                        //INSERCION DE FILAS PARA SALIDAS ADICIONALES
                        var rng = oSheet.Range("A" + (_Fila + 1).ToString() + ":N" + (_Fila + 1).ToString());
                        rng.InsertRowsBelow(MaxLines - 1);
                    }

                    _Fila++;

                    for (int i = _Fila; i <= _Fila + (MaxLines - 1); i++)
                    {
                        Salida++;

                        oSheet.Cell("A" + (i)).Value = "SALIDA " + Salida.ToString();
                    }

                    aviso = null;

                    for (int Columnas = 3; Columnas <= 9; Columnas++)
                    {

                        string aa = oSheet.Cell(_Fila - 1, Columnas).Value.ToString();
                        DateTime theDate = new DateTime(miDetalle[0].Fecha.Year, 1, 1).AddDays(Convert.ToInt32(aa) - 2);
                        string bb = theDate.Day.ToString();
                        List<CertificadoDetDTO> SubLista = miDetalle.FindAll(x => x.Dia.ToString() == bb && x.Fecha.Month.ToString("00") == theDate.ToString().Substring(3, 2)).ToList();

                        if (SubLista.Count > 0)
                        {
                            for (int i = 1; i <= SubLista.Count; i++)
                            {
                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", SubLista[i - 1].IdentifAviso));

                                if (oSheet.Cell(_Fila + i - 1, 2).Value == null || oSheet.Cell(_Fila + i, 2).Value.ToString() == "")
                                {
                                    oSheet.Cell(_Fila + i - 1, 2).Value = aviso.Duracion.ToString() + " SEG.";
                                }

                                oSheet.Cell(_Fila + i - 1, Columnas).Value = aviso.EtiquetaProd;

                            }

                            if (SubLista.Count > 1)
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=COUNTA({0}" + (_Fila).ToString() + ":{1}{2})", Celdas[Columnas].ToString(), Celdas[Columnas].ToString(), _Fila + MaxLines - 1);
                            }
                            else
                            {
                                oSheet.Cell(_Fila + MaxLines, Columnas).FormulaA1 = string.Format("=+COUNTA({0}" + (_Fila).ToString() + ")", Celdas[Columnas].ToString());
                            }
                        }
                    }

                    ///////////// fin de semanas //////////////

                    int Columna = 6; //COD. INGESTA
                    int Fila = 5;

                    while (1 == 1)
                    {
                        if (oSheet.Cell(Fila, Columna).Value != null && oSheet.Cell(Fila, Columna).Value.ToString() == "COD. INGESTA")
                        {

                            List<string> IdentifAvisos = new List<string>();

                            for (int i = 0; i <= miDetalle.Count - 1; i++)
                            {

                                if (IdentifAvisos.Count == 0)
                                {
                                    IdentifAvisos.Add(miDetalle[i].IdentifAviso);
                                }

                                bool lencontrado = false;

                                string scadena = miDetalle[i].IdentifAviso;

                                for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                                {
                                    if (IdentifAvisos[j] == scadena)
                                    {
                                        lencontrado = true;

                                        break;
                                    }
                                }

                                if (!lencontrado)
                                {
                                    IdentifAvisos.Add(miDetalle[i].IdentifAviso);

                                    break;
                                }

                            }

                            for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                            {

                                Fila++;

                                Columna = 3;

                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[i]));
                                oSheet.Cell(Fila, Columna).Value = aviso.EtiquetaProd;

                                DTO.PiezasArteDTO pieza = CRUDHelper.Read(string.Format("IdentifPieza = '{0}'", aviso.IdentifPieza),
                                                          BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.PiezasArte));

                                DTO.AnunInternosDTO ai = CRUDHelper.Read(string.Format("IdentifAnun = '{0}'", pieza.IdentifAnun),
                                                              BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AnunInternos));

                                oSheet.Cell(Fila, Columna + 1).Value = ai.Name;
                                oSheet.Cell(Fila, Columna + 2).Value = aviso.Zocalo;
                                oSheet.Cell(Fila, Columna + 3).Value = aviso.NroIngesta;

                                int cantsal = 0;

                                for (int j = 0; j <= miDetalle.Count - 1; j++)
                                {
                                    if (miDetalle[j].IdentifAviso == IdentifAvisos[i])
                                    {
                                        cantsal++;
                                    }
                                }

                                oSheet.Cell(Fila, Columna + 4).Value = cantsal;

                                Columna = 9;

                                decimal CostoPorSalida = miDetalle[0].CostoOp / miDetalle.Count;
                                oSheet.Cell(Fila, Columna).Value = CostoPorSalida;


                            }

                            Fila += 7;

                            oSheet.Cell(Fila, Columna).Value = _Espacio.Responsable;

                            Fila++;

                            DAO.SetUpDAO STUP = new DAO.SetUpDAO();

                            SetUpDTO setup = STUP.Read(1);

                            string sector = setup.Sector;

                            oSheet.Cell(Fila, Columna).Value = sector;

                            Fila++;

                            EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);

                            oSheet.Cell(Fila, Columna).Value = empresa.Name;

                            // telefonos //

                            for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                            {
                                AvisosIdAtenDTO aia = CRUDHelper.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[i]), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AvisosIdAten));
                                oSheet.Cell("E" + (Fila + i).ToString()).Value = "'" + aia.IdentifIdentAte;


                            }
                            //////////////


                            break;
                        }

                        Fila++;
                    }


                    break;


                }
#endregion
            }

            oWB.SaveAs(nomarchivo);
            oWB.Dispose();
            oSheet = null;
            oWB = null;
            GC.Collect(); 
        }
Example #14
0
        private void Export_Novy()
        {
            if (!InvokeRequired)
            {
                form.timer_ClearInfo.Stop();
            }
            else
            {
                this.BeginInvoke(new Action(() => form.timer_ClearInfo.Stop()));
            }
            form.infoBox.Text = form.jazyk.Message_Exportuji;
            form.Update();

            DateTime start;
            DateTime konec;

            over = false;
            List <ExportRow> exportRadky = new List <ExportRow>();

            int odec = 0;

            if (DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).DayOfWeek == DayOfWeek.Sunday && (int)DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).DayOfWeek == 0)
            {
                odec = 1;
            }

            if (radioButton3.Checked)
            {
                start = dateTimePicker1.Value;
                konec = dateTimePicker2.Value;
            }
            else if (radioButton1.Checked)
            {
                konec = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

                //tohle zrevidovat, jestli by nestačilo jen to Add day v catch bez try
                try
                {
                    start = new DateTime(DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).Year, DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).Month, DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).Day + odec);
                }
                catch
                {
                    start = new DateTime(DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).Year, DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).Month, DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).Day);
                    start = start.AddDays(odec);
                }
            }
            else
            {
                start = DateTime.Now.AddDays(-7);
                start = start.AddDays(-(int)(start.DayOfWeek - 1));
                start = new DateTime(start.Year, start.Month, start.Day);

                konec = new DateTime(start.Year, start.Month, start.Day).AddDays(6);
            }

            //Projít tickety splňující podmínku a zařadit je správně do exportu
            for (DateTime d = start; d <= konec; d = d.AddDays(1))
            {
                if (form.poDnech.ContainsKey(d))
                {
                    foreach (string s in form.poDnech[d].Keys)
                    {
                        foreach (Ticket t in form.poDnech[d][s])
                        {
                            DateTime pauzaDohromady = new DateTime();
                            DateTime cas            = new DateTime();
                            DateTime hrubyCas       = new DateTime();

                            for (int i = 0; i < t.PauzyDo.Count; i++)
                            {
                                if (t.PauzyDo[i].ToString("H:mm") != "0:00")
                                {
                                    pauzaDohromady = pauzaDohromady.AddHours(t.PauzyDo[i].Hour - t.PauzyOd[i].Hour).AddMinutes(t.PauzyDo[i].Minute - t.PauzyOd[i].Minute);
                                }
                            }

                            try
                            {
                                cas      = cas.AddHours((t.Do.Hour - t.Od.Hour) - pauzaDohromady.Hour).AddMinutes((t.Do.Minute - t.Od.Minute) - pauzaDohromady.Minute);
                                hrubyCas = form.RoundUp(cas, TimeSpan.FromMinutes(30));

                                //dny[d][t.TerpT].Add(t, hrubyCas);
                                string den = "";
                                switch (d.DayOfWeek)
                                {
                                case DayOfWeek.Monday: den = "Pondělí";
                                    break;

                                case DayOfWeek.Tuesday: den = "Úterý";
                                    break;

                                case DayOfWeek.Wednesday: den = "Středa";
                                    break;

                                case DayOfWeek.Thursday: den = "Čtvrtek";
                                    break;

                                case DayOfWeek.Friday: den = "Pátek";
                                    break;

                                case DayOfWeek.Saturday: den = "Sobota";
                                    break;

                                case DayOfWeek.Sunday: den = "Neděle";
                                    break;
                                }

                                ExportTyp et;
                                if (t.TypPrace == 0 || t.TypPrace == 2 || t.TypPrace == 8 || t.TypPrace == 12 || t.TypPrace == 16 || t.TypPrace == 20 || t.TypPrace == 24)
                                {
                                    et = ExportTyp.Normal;
                                }
                                else if (t.TypPrace == 1 || t.TypPrace == 6 || t.TypPrace == 10 || t.TypPrace == 15 || t.TypPrace == 18 || t.TypPrace == 23 || t.TypPrace == 27)
                                {
                                    et = ExportTyp.Holiday;
                                }
                                else if (t.TypPrace == 3 || t.TypPrace == 5 || t.TypPrace == 9 || t.TypPrace == 13 || t.TypPrace == 17 || t.TypPrace == 21 || t.TypPrace == 25)
                                {
                                    et = ExportTyp.Prescas;
                                }
                                else if (t.TypPrace == 4 || t.TypPrace == 7 || t.TypPrace == 11 || t.TypPrace == 14 || t.TypPrace == 19 || t.TypPrace == 22 || t.TypPrace == 26)
                                {
                                    et = ExportTyp.Compens;
                                }
                                else
                                {
                                    et = ExportTyp.Normal;
                                }

                                if (exportRadky.Count == 0)
                                {
                                    exportRadky.Add(new ExportRow());
                                }

                                List <int> toSkip = new List <int>();
                                if (t.CustomTerp == "")
                                {
                                    t.CustomTerp = Zakaznici.GetTerp(t.Zakaznik);
                                }
                                //když není task, tak defaultně incident 1.2.1 - nová verze by neměla umět uložit bez tasku
                                if (t.CustomTask == "")
                                {
                                    t.CustomTask = Zakaznici.Terpy.Get <NbtCompound>("Task").Get <NbtString>("Incident").Value;
                                }

                                //přiřazení ticketu ke správnému řádku a dni
                                for (int i = 0; i < exportRadky.Count; i++)
                                {
                                    if (exportRadky[i].Terp == null)
                                    {
                                        exportRadky[i].Terp = t.CustomTerp;
                                        exportRadky[i].Task = t.CustomTask;
                                        exportRadky[i].Typ  = et;
                                        exportRadky[i].Radek[den].Koment = t.ID + " " + t.Zakaznik + " " + t.Popis + "\r\n";
                                        decimal tCas = hrubyCas.Hour;
                                        if (hrubyCas.Minute == 30)
                                        {
                                            tCas += 0.5m;
                                        }
                                        exportRadky[i].Radek[den].Cas = tCas;
                                        break;
                                    }
                                    else if (exportRadky[i].Terp == t.CustomTerp && exportRadky[i].Task == t.CustomTask && exportRadky[i].Typ == et)
                                    {
                                        if ((exportRadky[i].Radek[den].Koment.Length + (t.ID + " " + t.Zakaznik + " " + t.Popis + "\r\n").Length < 240))
                                        {
                                            exportRadky[i].Radek[den].Koment += t.ID + " " + t.Zakaznik + " " + t.Popis + "\r\n";
                                            decimal tCas = hrubyCas.Hour;
                                            if (hrubyCas.Minute == 30)
                                            {
                                                tCas += 0.5m;
                                            }
                                            exportRadky[i].Radek[den].Cas += tCas;
                                            break;
                                        }
                                        else
                                        {
                                            exportRadky.Add(new ExportRow());
                                            continue;
                                        }
                                    }
                                    else if (i < exportRadky.Count - 1)
                                    {
                                        continue;
                                    }
                                    exportRadky.Add(new ExportRow());
                                }
                            }
                            catch
                            {
                                MessageBox.Show(form.jazyk.Windows_Export_Ticket + " " + t.ID + " - " + t.Zakaznik + ", " + form.jazyk.Windows_Export_NaKteremJsiPracoval + " " + t.Datum.ToString("d.MM.yyyy") + ", " + form.jazyk.Windows_Export_Neukoncen);
                            }
                        }
                    }
                }
            }

            //přepočet času na 8h
            //celkový čas normálních ticketů (statní se neupravují)
            Dictionary <string, decimal> casy = new Dictionary <string, decimal> {
                { "Pondělí", 0 }, { "Úterý", 0 }, { "Středa", 0 }, { "Čtvrtek", 0 }, { "Pátek", 0 }, { "Sobota", 0 }, { "Neděle", 0 }
            };

            foreach (ExportRow s in exportRadky)
            {
                if (s.Typ == ExportTyp.Normal)
                {
                    casy["Pondělí"] += s.Radek["Pondělí"].Cas;
                    casy["Úterý"]   += s.Radek["Úterý"].Cas;
                    casy["Středa"]  += s.Radek["Středa"].Cas;
                    casy["Čtvrtek"] += s.Radek["Čtvrtek"].Cas;
                    casy["Pátek"]   += s.Radek["Pátek"].Cas;
                    casy["Sobota"]  += s.Radek["Sobota"].Cas;
                    casy["Neděle"]  += s.Radek["Neděle"].Cas;
                }
            }

            //výběr řádků, co se upraví čas
            foreach (string cs in casy.Keys)
            {
                if (casy[cs] == 8 || casy[cs] == 0)
                {
                    continue;
                }
                else if (casy[cs] < 8)
                {
                    Dictionary <int, decimal> pridat = new Dictionary <int, decimal>();

                    for (int i = 0; i < exportRadky.Count; i++)
                    {
                        if (exportRadky[i].Typ == ExportTyp.Normal && exportRadky[i].Radek[cs].Cas > 0)
                        {
                            pridat.Add(i, exportRadky[i].Radek[cs].Cas);
                        }
                    }

                    pridat = pridat.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

                    decimal zbyva         = 8 - casy[cs];
                    decimal prumerNaRadek = Math.Ceiling((zbyva / pridat.Count) / 0.5m) * 0.5m;

                    //úprava času
                    int index = 0;
                    for (decimal d = zbyva; d > 0; d -= prumerNaRadek)
                    {
                        if (d - prumerNaRadek < 0)
                        {
                            prumerNaRadek = d;
                        }

                        pridat[pridat.Keys.ElementAt(index)] += prumerNaRadek;

                        index++;
                        zbyva -= prumerNaRadek;
                    }
                    foreach (int newI in pridat.Keys)
                    {
                        exportRadky[newI].Radek[cs].Cas = pridat[newI];
                    }
                }
                else if (casy[cs] > 8)
                {
                    Dictionary <int, decimal> ubrat = new Dictionary <int, decimal>();

                    for (int i = 0; i < exportRadky.Count; i++)
                    {
                        if (exportRadky[i].Typ == ExportTyp.Normal && exportRadky[i].Radek[cs].Cas > 0.5m)
                        {
                            ubrat.Add(i, exportRadky[i].Radek[cs].Cas);
                        }
                    }

                    ubrat = ubrat.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
                    decimal zbyva         = casy[cs] - 8;
                    decimal prumerNaRadek = Math.Ceiling((zbyva / ubrat.Count) / 0.5m) * 0.5m;

                    //úprava času
                    int index = 0;
                    for (decimal d = zbyva; d > 0; d -= prumerNaRadek)
                    {
                        if (d - prumerNaRadek < 0)
                        {
                            prumerNaRadek = d;
                        }

                        ubrat[ubrat.Keys.ElementAt(index)] -= prumerNaRadek;

                        index++;
                        zbyva -= prumerNaRadek;
                    }
                    foreach (int newI in ubrat.Keys)
                    {
                        exportRadky[newI].Radek[cs].Cas = ubrat[newI];
                    }
                }
            }

            //export do souboru
            //pro excel
            File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Ticketnik\\tmp_export.xlsx", Properties.Resources.mytime_template);

            Excel.XLWorkbook   export      = new Excel.XLWorkbook(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Ticketnik\\tmp_export.xlsx");
            Excel.IXLWorksheet exportSheet = export.Worksheet(1);

            NumberFormatInfo nfi = new NumberFormatInfo();

            nfi.NumberDecimalSeparator = ".";

            int row = 2;

            foreach (ExportRow s in exportRadky)
            {
                if (s.Terp != null)
                {
                    //project
                    exportSheet.Cell(row, 1).Value = s.Terp;
                    //project name
                    exportSheet.Cell(row, 2).Value = "najdiSiSam";
                    //task
                    exportSheet.Cell(row, 3).SetValue(s.Task);
                    //task name
                    exportSheet.Cell(row, 4).Value = "TyVisCo";
                    //type
                    exportSheet.Cell(row, 5).Value = s.GetTyp();
                    //pondělí (čas, comment)
                    exportSheet.Cell(row, 6).Value = s.Radek["Pondělí"].Cas.ToString() == "0" ? "" : s.Radek["Pondělí"].Cas.ToString(nfi);
                    exportSheet.Cell(row, 7).Value = s.Radek["Pondělí"].Koment.Replace("\t", " ").Replace("\"", "");
                    //úterý
                    exportSheet.Cell(row, 10).Value = s.Radek["Úterý"].Cas.ToString() == "0" ? "" : s.Radek["Úterý"].Cas.ToString(nfi);
                    exportSheet.Cell(row, 11).Value = s.Radek["Úterý"].Koment.Replace("\t", " ").Replace("\"", "");
                    //středa
                    exportSheet.Cell(row, 14).Value = s.Radek["Středa"].Cas.ToString() == "0" ? "" : s.Radek["Středa"].Cas.ToString(nfi);
                    exportSheet.Cell(row, 15).Value = s.Radek["Středa"].Koment.Replace("\t", " ").Replace("\"", "");
                    //čtvrtek
                    exportSheet.Cell(row, 18).Value = s.Radek["Čtvrtek"].Cas.ToString() == "0" ? "" : s.Radek["Čtvrtek"].Cas.ToString(nfi);
                    exportSheet.Cell(row, 19).Value = s.Radek["Čtvrtek"].Koment.Replace("\t", " ").Replace("\"", "");
                    //pátek
                    exportSheet.Cell(row, 22).Value = s.Radek["Pátek"].Cas.ToString() == "0" ? "" : s.Radek["Pátek"].Cas.ToString(nfi);
                    exportSheet.Cell(row, 23).Value = s.Radek["Pátek"].Koment.Replace("\t", " ").Replace("\"", "");
                    //sobota
                    exportSheet.Cell(row, 26).Value = s.Radek["Sobota"].Cas.ToString() == "0" ? "" : s.Radek["Sobota"].Cas.ToString(nfi);
                    exportSheet.Cell(row, 27).Value = s.Radek["Sobota"].Koment.Replace("\t", " ").Replace("\"", "");
                    //neděle
                    exportSheet.Cell(row, 30).Value = s.Radek["Neděle"].Cas.ToString() == "0" ? "" : s.Radek["Neděle"].Cas.ToString(nfi);
                    exportSheet.Cell(row, 31).Value = s.Radek["Neděle"].Koment.Replace("\t", " ").Replace("\"", "");

                    row++;
                }
            }

            export.Save();
            export.Dispose();

            form.infoBox.Text = "";

            saveFileDialog1.AddExtension = true;
            saveFileDialog1.DefaultExt   = "xlsx";
            saveFileDialog1.Filter       = "Excel|*.xlsx";
            saveFileDialog1.FileName     = "MyTime Info.xlsx";
            saveFileDialog1.ShowDialog();
        }
Example #15
0
        private void button_statis_outputExcel_Click(object sender, EventArgs e)
        {
            string strError = "";
            int nRet = 0;

            bool bLaunchExcel = true;
            this.ClearMessage();

            // 询问文件名
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Title = "请指定要输出的 Excel 文件名";
            dlg.CreatePrompt = false;
            dlg.OverwritePrompt = true;
            // dlg.FileName = this.ExportExcelFilename;
            // dlg.InitialDirectory = Environment.CurrentDirectory;
            dlg.Filter = "Excel 文件 (*.xlsx)|*.xlsx|All files (*.*)|*.*";

            dlg.RestoreDirectory = true;

            if (dlg.ShowDialog() != DialogResult.OK)
                return;

            XLWorkbook doc = null;

            try
            {
                doc = new XLWorkbook(XLEventTracking.Disabled);
                File.Delete(dlg.FileName);
            }
            catch (Exception ex)
            {
                strError = "new XLWorkbook() exception: " + ExceptionUtil.GetAutoText(ex);
                goto ERROR1;
            }

            this.ShowMessage("正在创建 Excel 报表");

            stop.Style = StopStyle.EnableHalfStop;
            stop.OnStop += new StopEventHandler(this.DoStop);
            stop.Initial("正在创建 Excel 报表 ...");
            stop.BeginLoop();

            EnableControls(false);
            this.listView_baseList_records.Enabled = false;
            this.listView_inventoryList_records.Enabled = false;
            try
            {
                List<string> output_columns = StringUtil.SplitList(this.OutputColumns);

                // return:
                //      -1  出错
                //      0   放弃或中断
                //      1   成功
                nRet = CreateLostSheet(
                    stop,
                    doc,
                    output_columns,
                    out strError);
                if (nRet != 1)
                    goto ERROR1;

                // return:
                //      -1  出错
                //      0   放弃或中断
                //      1   成功
                nRet = CreateOutOfRangeSheet(
                    stop,
                    doc,
                    output_columns,
                    out strError);
                if (nRet != 1)
                    goto ERROR1;

                // return:
                //      -1  出错
                //      0   放弃或中断
                //      1   成功
                nRet = CreateBorrowedSheet(
                    stop,
                    doc,
                    output_columns,
                    out strError);
                if (nRet != 1)
                    goto ERROR1;

                // return:
                //      -1  出错
                //      0   放弃或中断
                //      1   成功
                nRet = CreateVerifiedSheet(
                    stop,
                    doc,
                    output_columns,
                    out strError);
                if (nRet != 1)
                    goto ERROR1;
            }
            finally
            {
                EnableControls(true);
                this.listView_baseList_records.Enabled = true;
                this.listView_inventoryList_records.Enabled = true;

                stop.EndLoop();
                stop.OnStop -= new StopEventHandler(this.DoStop);
                stop.Initial("");
                stop.HideProgress();
                stop.Style = StopStyle.None;

                if (doc != null)
                {
                    doc.SaveAs(dlg.FileName);
                    doc.Dispose();
                }

                if (bLaunchExcel)
                {
                    try
                    {
                        System.Diagnostics.Process.Start(dlg.FileName);
                    }
                    catch
                    {

                    }
                }

            }

            this.ShowMessage("创建完成", "green", true);
            return;
        ERROR1:
            // MessageBox.Show(this, strError);
            this.ShowMessage(strError, "red", true);
        }
Example #16
0
        // return:
        //      -1  出错
        //      0   用户中断
        //      1   成功
        public int CreateReaderDetailExcelFile(List<string> reader_barcodes,
            bool bLaunchExcel,
            out string strError)
        {
            strError = "";
            int nRet = 0;

            // 询问文件名
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Title = "请指定要输出的 Excel 文件名";
            dlg.CreatePrompt = false;
            dlg.OverwritePrompt = true;
            // dlg.FileName = this.ExportExcelFilename;
            // dlg.InitialDirectory = Environment.CurrentDirectory;
            dlg.Filter = "Excel 文件 (*.xlsx)|*.xlsx|All files (*.*)|*.*";

            dlg.RestoreDirectory = true;

            if (dlg.ShowDialog() != DialogResult.OK)
                return 0;

            XLWorkbook doc = null;

            try
            {
                doc = new XLWorkbook(XLEventTracking.Disabled);
                File.Delete(dlg.FileName);
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                return -1;
            }

            IXLWorksheet sheet = null;
            sheet = doc.Worksheets.Add("表格");

            // TODO: sheet 可以按照单位来区分。例如按照班级

            stop.Style = StopStyle.EnableHalfStop;
            stop.OnStop += new StopEventHandler(this.DoStop);
            stop.Initial("导出读者详情 ...");
            stop.BeginLoop();

            EnableControls(false);
            this.listView_records.Enabled = false;

            try
            {
                if (stop != null)
                    stop.SetProgressRange(0, reader_barcodes.Count);

                // 每个列的最大字符数
                List<int> column_max_chars = new List<int>();

                // TODO: 表的标题,创建时间

                int nRowIndex = 3;  // 空出前两行
                int nColIndex = 1;

                int nReaderIndex = 0;
                foreach (string strBarcode in reader_barcodes)
                {
                    Application.DoEvents();	// 出让界面控制权

                    if (stop != null)
                    {
                        if (stop.State != 0)
                            return 0;
                    }

                    if (string.IsNullOrEmpty(strBarcode) == true)
                        continue;

                    // 获得读者记录
                    byte[] baTimestamp = null;
                    string strOutputRecPath = "";

                    stop.SetMessage("正在处理读者记录 " + strBarcode + " ...");

                    string[] results = null;
                    long lRet = Channel.GetReaderInfo(
                        stop,
                        strBarcode,
                        "advancexml,advancexml_borrow_bibliosummary,advancexml_overdue_bibliosummary", // advancexml_history_bibliosummary
                        out results,
                        out strOutputRecPath,
                        out baTimestamp,
                        out strError);
                    if (lRet == -1)
                        return -1;

                    if (lRet == 0)
                        return -1;

                    if (lRet > 1)   // 不可能发生吧?
                    {
                        strError = "读者证条码号 " + strBarcode + " 命中记录 " + lRet.ToString() + " 条,放弃装入读者记录。\r\n\r\n注意这是一个严重错误,请系统管理员尽快排除。";
                        return -1;
                    }
                    if (results == null || results.Length < 1)
                    {
                        strError = "返回的results不正常。";
                        return -1;
                    }
                    string strXml = results[0];

                    XmlDocument dom = new XmlDocument();
                    try
                    {
                        dom.LoadXml(strXml);
                    }
                    catch (Exception ex)
                    {
                        strError = "装载读者记录 XML 到 DOM 时发生错误: " + ex.Message;
                        return -1;
                    }

                    // 
                    //
                    OutputReaderInfo(sheet,
            dom,
            nReaderIndex,
            ref nRowIndex,
            ref column_max_chars);

                    // 输出在借册表格
                    OutputBorrows(sheet,
            dom,
            ref nRowIndex,
            ref column_max_chars);

                    // 输出违约金表格
                    OutputOverdues(sheet,
            dom,
            ref nRowIndex,
            ref column_max_chars);

                    nRowIndex++;    // 读者之间的空行

                    nReaderIndex++;
                    if (stop != null)
                        stop.SetProgressValue(nReaderIndex);
                }

                {
                    if (stop != null)
                        stop.SetMessage("正在调整列宽度 ...");
                    Application.DoEvents();

                    //double char_width = GetAverageCharPixelWidth(list);

                    // 字符数太多的列不要做 width auto adjust
                    foreach (IXLColumn column in sheet.Columns())
                    {
                        int MAX_CHARS = 50;   // 60

                        int nIndex = column.FirstCell().Address.ColumnNumber - 1;
                        if (nIndex >= column_max_chars.Count)
                            break;
                        int nChars = column_max_chars[nIndex];

                        if (nIndex == 1)
                        {
                            column.Width = 10;
                            continue;
                        }

                        if (nIndex == 3)
                            MAX_CHARS = 50;
                        else
                            MAX_CHARS = 24;

                        if (nChars < MAX_CHARS)
                            column.AdjustToContents();
                        else
                            column.Width = Math.Min(MAX_CHARS, nChars);

                        //else
                        //    column.Width = (double)list.Columns[i].Width / char_width;  // Math.Min(MAX_CHARS, nChars);
                    }
                }

            }
            finally
            {
                EnableControls(true);
                this.listView_records.Enabled = true;

                stop.EndLoop();
                stop.OnStop -= new StopEventHandler(this.DoStop);
                stop.Initial("");
                stop.HideProgress();
                stop.Style = StopStyle.None;

                if (doc != null)
                {
                    doc.SaveAs(dlg.FileName);
                    doc.Dispose();
                }

                if (bLaunchExcel)
                {
                    try
                    {
                        System.Diagnostics.Process.Start(dlg.FileName);
                    }
                    catch
                    {

                    }
                }

            }
            return 0;
        }
Example #17
0
        // return:
        //      -1  出错
        //      0   用户中断
        //      1   成功
        public int CreateReaderDetailExcelFile(List<string> reader_barcodes,
            bool bLaunchExcel,
            out string strError)
        {
            strError = "";
            //int nRet = 0;

            ExportPatronExcelDialog dlg = new ExportPatronExcelDialog();
            MainForm.SetControlFont(dlg, this.Font, false);
            dlg.OverwritePrompt = true;
            dlg.UiState = this.MainForm.AppInfo.GetString(
        "ReaderSearchForm",
        "ExportPatronExcelDialog_uiState",
        "");

            this.MainForm.AppInfo.LinkFormState(dlg, "ReaderSearchForm_ExportPatronExcelDialog_uiState_state");
            dlg.ShowDialog(this);

            this.MainForm.AppInfo.SetString(
"ReaderSearchForm",
"ExportPatronExcelDialog_uiState",
dlg.UiState);

            if (dlg.DialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                strError = "放弃操作";
                return 0;
            }

            string strTimeRange = "";

            try
            {
                strTimeRange = GetTimeRange(dlg.ChargingHistoryDateRange);
            }
            catch (Exception ex)
            {
                strError = "日期范围字符串 '" + dlg.ChargingHistoryDateRange + "' 格式不合法: " + ex.Message;
                return -1;
            }

            XLWorkbook doc = null;
            try
            {
                doc = new XLWorkbook(XLEventTracking.Disabled);
                File.Delete(dlg.FileName);
            }
            catch (Exception ex)
            {
                strError = "ReaderSearchForm new XLWorkbook() {39D0940F-33FF-4A10-8F61-1FFFEEBFF4D0} exception: " + ExceptionUtil.GetAutoText(ex);
                return -1;
            }

            IXLWorksheet sheet = null;
            sheet = doc.Worksheets.Add("表格");

            // 每个列的最大字符数
            List<int> column_max_chars = new List<int>();

            // TODO: 表的标题,创建时间

            int nRowIndex = 3;  // 空出前两行
            //int nColIndex = 1;

            int nReaderIndex = 0;

            try
            {
                // return:
                //      -1  出错。包括用户中断的情况
                //      >=0 实际处理的读者记录数
                int nRet = this.ProcessPatrons(
                    reader_barcodes,
                    "advancexml,advancexml_borrow_bibliosummary,advancexml_overdue_bibliosummary", // advancexml_history_bibliosummary
                    (strRecPath, dom, timestamp) =>
                    {
                        this.ShowMessage("正在处理读者记录 " + strRecPath);

                        string strBarcode = DomUtil.GetElementText(dom.DocumentElement, "barcode");

                        // 
                        if (dlg.ExportReaderInfo)
                        {
                            OutputReaderInfo(sheet,
                    dom,
                    nReaderIndex,
                    ref nRowIndex,
                    ref column_max_chars);
                        }

                        // 输出在借册表格
                        if (dlg.ExportBorrowInfo)
                        {
                            OutputBorrows(sheet,
                    dom,
                    this.MainForm.GetBiblioSummary,
                    true,
                    ref nRowIndex,
                    ref column_max_chars);
                        }

                        // 输出违约金表格
                        if (dlg.ExportOverdueInfo)
                        {
                            OutputOverdues(sheet,
                    dom,
                    this.MainForm.GetBiblioSummary,
                    ref nRowIndex,
                    ref column_max_chars);
                        }

                        if (dlg.ExportChargingHistory)
                        {
                            try
                            {
                                ChargingHistoryLoader history_loader = new ChargingHistoryLoader();
                                history_loader.Channel = this.Channel;
                                history_loader.Stop = this.stop;
                                history_loader.PatronBarcode = strBarcode;
                                history_loader.TimeRange = strTimeRange;
                                history_loader.Actions = "return,lost";
                                history_loader.Order = "descending";

                                CacheableBiblioLoader summary_loader = new CacheableBiblioLoader();
                                summary_loader.Channel = this.Channel;
                                summary_loader.Stop = this.stop;
                                summary_loader.Format = "summary";
                                summary_loader.GetBiblioInfoStyle = GetBiblioInfoStyle.None;
                                // summary_loader.RecPaths = biblio_recpaths;

                                // 输出借阅历史表格
                                // 可能会抛出异常,例如权限不够
                                OutputBorrowHistory(sheet,
                        dom,
                        history_loader,
                                    // this.MainForm.GetBiblioSummary,
                        summary_loader,
                        ref nRowIndex,
                        ref column_max_chars);
                            }
                            catch (Exception ex)
                            {
                                string strErrorText = "输出借阅历史时出现异常: " + ex.Message;
                                throw new Exception(strErrorText);
                            }
                        }

                        nRowIndex++;    // 读者之间的空行

                        nReaderIndex++;
                        return true;
                    },
                    out strError);
                if (nRet == -1)
                    return -1;

                {
                    if (stop != null)
                        stop.SetMessage("正在调整列宽度 ...");
                    Application.DoEvents();

                    //double char_width = GetAverageCharPixelWidth(list);

                    // 字符数太多的列不要做 width auto adjust
                    foreach (IXLColumn column in sheet.Columns())
                    {
                        int MAX_CHARS = 50;   // 60

                        int nIndex = column.FirstCell().Address.ColumnNumber - 1;
                        if (nIndex >= column_max_chars.Count)
                            break;
                        int nChars = column_max_chars[nIndex];

                        if (nIndex == 1)
                        {
                            column.Width = 10;
                            continue;
                        }

                        if (nIndex == 3)
                            MAX_CHARS = 50;
                        else
                            MAX_CHARS = 24;

                        if (nChars < MAX_CHARS)
                            column.AdjustToContents();
                        else
                            column.Width = Math.Min(MAX_CHARS, nChars);

                        //else
                        //    column.Width = (double)list.Columns[i].Width / char_width;  // Math.Min(MAX_CHARS, nChars);
                    }
                }

                this.ShowMessage("共导出读者记录 " + nReaderIndex + " 个", "green", true);
            }
            catch (Exception ex)
            {
                strError = "CreateDetailExcelFile() 出现异常: " + ExceptionUtil.GetExceptionText(ex);
                return -1;
            }
            finally
            {
                if (stop != null)
                    stop.SetMessage("");

                if (doc != null)
                {
                    doc.SaveAs(dlg.FileName);
                    doc.Dispose();
                }

                if (bLaunchExcel)
                {
                    try
                    {
                        System.Diagnostics.Process.Start(dlg.FileName);
                    }
                    catch
                    {

                    }
                }
            }

            // TODO: sheet 可以按照单位来区分。例如按照班级
            return 1;
        }
Example #18
0
        // return:
        //      -1  出错
        //      0   用户中断
        //      1   成功
        public int CreateReaderDetailExcelFile(List<string> reader_barcodes,
            bool bLaunchExcel,
            out string strError)
        {
            strError = "";
            //int nRet = 0;

            ExportPatronExcelDialog dlg = new ExportPatronExcelDialog();
            MainForm.SetControlFont(dlg, this.Font, false);
            dlg.OverwritePrompt = true;
            dlg.UiState = this.MainForm.AppInfo.GetString(
        "ReaderSearchForm",
        "ExportPatronExcelDialog_uiState",
        "");

            this.MainForm.AppInfo.LinkFormState(dlg, "ReaderSearchForm_ExportPatronExcelDialog_uiState_state");
            dlg.ShowDialog(this);

            this.MainForm.AppInfo.SetString(
"ReaderSearchForm",
"ExportPatronExcelDialog_uiState",
dlg.UiState);

            if (dlg.DialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                strError = "放弃操作";
                return 0;
            }

#if NO
            // 提醒覆盖文件
            if (File.Exists(dlg.FileName) == true)
            {
                DialogResult result = MessageBox.Show(this,
                    "文件 '" + dlg.FileName + "' 已经存在。继续操作将覆盖此文件。\r\n\r\n请问是否要覆盖此文件? (OK 覆盖;Cancel 放弃操作)",
                    "ReaderSearchForm",
                    MessageBoxButtons.OKCancel,
                    MessageBoxIcon.Question,
                    MessageBoxDefaultButton.Button1);
                if (result == DialogResult.Cancel)
                {
                    strError = "放弃操作";
                    return 0;
                }
            }
#endif

            string strTimeRange = "";

            try
            {
                strTimeRange = GetTimeRange(dlg.ChargingHistoryDateRange);
            }
            catch (Exception ex)
            {
                strError = "日期范围字符串 '" + dlg.ChargingHistoryDateRange + "' 格式不合法: " + ex.Message;
                return -1;
            }

#if NO
            // 询问文件名
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Title = "请指定要输出的 Excel 文件名";
            dlg.CreatePrompt = false;
            dlg.OverwritePrompt = true;
            // dlg.FileName = this.ExportExcelFilename;
            // dlg.InitialDirectory = Environment.CurrentDirectory;
            dlg.Filter = "Excel 文件 (*.xlsx)|*.xlsx|All files (*.*)|*.*";

            dlg.RestoreDirectory = true;

            if (dlg.ShowDialog() != DialogResult.OK)
                return 0;
#endif

            XLWorkbook doc = null;
            try
            {
                doc = new XLWorkbook(XLEventTracking.Disabled);
                File.Delete(dlg.FileName);
            }
            catch (Exception ex)
            {
                strError = "ReaderSearchForm new XLWorkbook() {39D0940F-33FF-4A10-8F61-1FFFEEBFF4D0} exception: " + ExceptionUtil.GetAutoText(ex);
                return -1;
            }

            IXLWorksheet sheet = null;
            sheet = doc.Worksheets.Add("表格");

            // TODO: sheet 可以按照单位来区分。例如按照班级

            stop.Style = StopStyle.EnableHalfStop;
            stop.OnStop += new StopEventHandler(this.DoStop);
            stop.Initial("导出读者详情 ...");
            stop.BeginLoop();

            EnableControls(false);
            this.listView_records.Enabled = false;

            try
            {
                if (stop != null)
                    stop.SetProgressRange(0, reader_barcodes.Count);

                // 每个列的最大字符数
                List<int> column_max_chars = new List<int>();

                // TODO: 表的标题,创建时间

                int nRowIndex = 3;  // 空出前两行
                //int nColIndex = 1;

                int nReaderIndex = 0;
                foreach (string strBarcode in reader_barcodes)
                {
                    Application.DoEvents();	// 出让界面控制权

                    if (stop != null && stop.State != 0)
                    {
                        strError = "用户中断";
                        return 0;
                    }

                    if (string.IsNullOrEmpty(strBarcode) == true)
                        continue;

                    // 获得读者记录
                    byte[] baTimestamp = null;
                    string strOutputRecPath = "";

                    stop.SetMessage("正在处理读者记录 " + strBarcode + " ...");

                    string[] results = null;
                    long lRet = Channel.GetReaderInfo(
                        stop,
                        strBarcode,
                        "advancexml,advancexml_borrow_bibliosummary,advancexml_overdue_bibliosummary", // advancexml_history_bibliosummary
                        out results,
                        out strOutputRecPath,
                        out baTimestamp,
                        out strError);
                    if (lRet == -1)
                        return -1;

                    if (lRet == 0)
                        return -1;

                    if (lRet > 1)   // 不可能发生吧?
                    {
                        strError = "读者证条码号 " + strBarcode + " 命中记录 " + lRet.ToString() + " 条,放弃装入读者记录。\r\n\r\n注意这是一个严重错误,请系统管理员尽快排除。";
                        return -1;
                    }
                    if (results == null || results.Length < 1)
                    {
                        strError = "返回的results不正常。";
                        return -1;
                    }
                    string strXml = results[0];

                    XmlDocument dom = new XmlDocument();
                    try
                    {
                        dom.LoadXml(strXml);
                    }
                    catch (Exception ex)
                    {
                        strError = "装载读者记录 XML 到 DOM 时发生错误: " + ex.Message;
                        return -1;
                    }

                    // 
                    if (dlg.ExportReaderInfo)
                    {
                        OutputReaderInfo(sheet,
                dom,
                nReaderIndex,
                ref nRowIndex,
                ref column_max_chars);
                    }

                    // 输出在借册表格
                    if (dlg.ExportBorrowInfo)
                    {
                        OutputBorrows(sheet,
                dom,
                this.MainForm.GetBiblioSummary,
                true,
                ref nRowIndex,
                ref column_max_chars);
                    }

                    // 输出违约金表格
                    if (dlg.ExportOverdueInfo)
                    {
                        OutputOverdues(sheet,
                dom,
                this.MainForm.GetBiblioSummary,
                ref nRowIndex,
                ref column_max_chars);
                    }

                    if (dlg.ExportChargingHistory)
                    {
                        try
                        {
                            ChargingHistoryLoader history_loader = new ChargingHistoryLoader();
                            history_loader.Channel = this.Channel;
                            history_loader.Stop = this.stop;
                            history_loader.PatronBarcode = strBarcode;
                            history_loader.TimeRange = strTimeRange;
                            history_loader.Actions = "return,lost";
                            history_loader.Order = "descending";

                            CacheableBiblioLoader summary_loader = new CacheableBiblioLoader();
                            summary_loader.Channel = this.Channel;
                            summary_loader.Stop = this.stop;
                            summary_loader.Format = "summary";
                            summary_loader.GetBiblioInfoStyle = GetBiblioInfoStyle.None;
                            // summary_loader.RecPaths = biblio_recpaths;

                            // 输出借阅历史表格
                            OutputBorrowHistory(sheet,
                    dom,
                    history_loader,
                                // this.MainForm.GetBiblioSummary,
                    summary_loader,
                    ref nRowIndex,
                    ref column_max_chars);
                        }
                        catch (Exception ex)
                        {
                            strError = "输出借阅历史时出现异常: " + ex.Message;
                            return -1;
                        }
                    }

                    nRowIndex++;    // 读者之间的空行

                    nReaderIndex++;
                    if (stop != null)
                        stop.SetProgressValue(nReaderIndex);
                }

                {
                    if (stop != null)
                        stop.SetMessage("正在调整列宽度 ...");
                    Application.DoEvents();

                    //double char_width = GetAverageCharPixelWidth(list);

                    // 字符数太多的列不要做 width auto adjust
                    foreach (IXLColumn column in sheet.Columns())
                    {
                        int MAX_CHARS = 50;   // 60

                        int nIndex = column.FirstCell().Address.ColumnNumber - 1;
                        if (nIndex >= column_max_chars.Count)
                            break;
                        int nChars = column_max_chars[nIndex];

                        if (nIndex == 1)
                        {
                            column.Width = 10;
                            continue;
                        }

                        if (nIndex == 3)
                            MAX_CHARS = 50;
                        else
                            MAX_CHARS = 24;

                        if (nChars < MAX_CHARS)
                            column.AdjustToContents();
                        else
                            column.Width = Math.Min(MAX_CHARS, nChars);

                        //else
                        //    column.Width = (double)list.Columns[i].Width / char_width;  // Math.Min(MAX_CHARS, nChars);
                    }
                }
            }
            finally
            {
                EnableControls(true);
                this.listView_records.Enabled = true;

                stop.EndLoop();
                stop.OnStop -= new StopEventHandler(this.DoStop);
                stop.Initial("");
                stop.HideProgress();
                stop.Style = StopStyle.None;

                if (doc != null)
                {
                    doc.SaveAs(dlg.FileName);
                    doc.Dispose();
                }

                if (bLaunchExcel)
                {
                    try
                    {
                        System.Diagnostics.Process.Start(dlg.FileName);
                    }
                    catch
                    {

                    }
                }

            }
            return 1;
        }
Example #19
0
 private static void CreateSummaryTable(IXLCell scr)
 {
     XLWorkbook template = new XLWorkbook(Application.StartupPath + Helper.GetTemplateFileName());
       var sheet = template.Worksheet("Template");
       var summaryTableRange = sheet.Range(237, 8, 242, 17);
       summaryTableRange.CopyTo(scr);
       template.Dispose();
 }
        public void Cabecera_OP_Calendario_Descriptivo(string nomarchivo)
        {

            ////// ClosedXML ////////
            XLWorkbook oWB = new XLWorkbook(nomarchivo);
            var oSheet = oWB.Worksheet(1);

            switch (_Estado.ToUpper())
            {
                case "ORDENADO": {

                    EmpresaDTO empresa        = new DAO.EmpresaDAO().Read(1);
                    OrdenadoCabDTO miCabecera = (OrdenadoCabDTO)_Cabecera;

                    DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));
                    string[] Meses         = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                    string aniomes         = miCabecera.AnoMes.ToString();


                    //ARMADO DE CALENDARIO - MEJORAR
                    int mes       = Convert.ToInt32(aniomes.Substring(4, 2));
                    int anio      = Convert.ToInt32(aniomes.Substring(0, 4));
                    int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);

                    string[] DiasSemana = { "", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };
                    int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                    int PrimerDiaMes    = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);

                    int dia = PrimerDiaMes - PrimerDiaSemana + 2;

                    for (int Filas = 20; Filas <= 40; Filas = Filas + 5)
                    {
                        for (int Columnas = 2; Columnas <= 8; Columnas++)
                        {
                            DateTime theDate = new DateTime(anio, 1, 1).AddDays(dia-2);

                            oSheet.Cell(Filas, Columnas).Value = theDate;

                            dia++;
                        }
                    }

                    oSheet.Cells("C5").Value  = "Orden de Publicidad - " + miCabecera.IdentifEspacio;
                    oSheet.Cells("B9").Value  = miCabecera.PautaId;
                    oSheet.Cells("B10").Value = medio.Name;
                    oSheet.Cells("B11").Value = _Espacio.Name;
                    oSheet.Cells("B12").Value = "'" + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);
                    oSheet.Cells("B13").Value = _Espacio.Contacto == null ? "" : _Espacio.Contacto.ToUpper();
                    oSheet.Cells("A14").Value = "EMAIL: ";
                    oSheet.Cells("B14").Value = _Espacio.Email == null ? "" : _Espacio.Email;
                    FrecuenciaDTO frecuencia  = CRUDHelper.Read(string.Format("IdentifFrecuencia = '{0}'", miCabecera.IdentifFrecuencia), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.Frecuencia));
                    oSheet.Cells("B15").Value = frecuencia.Name + " de " + _Espacio.HoraInicio + " a " + _Espacio.HoraFin + "hs.";

                    break; }
                case "ESTIMADO": {

                    EmpresaDTO empresa        = new DAO.EmpresaDAO().Read(1);
                    EstimadoCabDTO miCabecera = (EstimadoCabDTO)_Cabecera;

                    DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));
                    string[] Meses         = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                    string aniomes         = miCabecera.AnoMes.ToString();

                    //ARMADO DE CALENDARIO - MEJORAR
                    int mes       = Convert.ToInt32(aniomes.Substring(4, 2));
                    int anio      = Convert.ToInt32(aniomes.Substring(0, 4));
                    int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);

                    string[] DiasSemana = { "", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };
                    int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                    int PrimerDiaMes    = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);

                    int dia = PrimerDiaMes - PrimerDiaSemana + 2;

                    for (int Filas = 20; Filas <= 40; Filas = Filas + 5)
                    {
                        for (int Columnas = 2; Columnas <= 8; Columnas++)
                        {
                            DateTime theDate = new DateTime(anio, 1, 1).AddDays(dia - 2);

                            oSheet.Cell(Filas, Columnas).Value = theDate;

                            dia++;
                        }
                    }

                    oSheet.Cells("C5").Value  = "Orden de Publicidad - " + miCabecera.IdentifEspacio;
                    oSheet.Cells("B9").Value  = miCabecera.PautaId;
                    oSheet.Cells("B10").Value = medio.Name;
                    oSheet.Cells("B11").Value = _Espacio.Name;
                    oSheet.Cells("B12").Value = "'" + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);
                    oSheet.Cells("B13").Value = _Espacio.Contacto == null ? "" : _Espacio.Contacto.ToUpper();
                    oSheet.Cells("A14").Value = "EMAIL: ";
                    oSheet.Cells("B14").Value = _Espacio.Email == null ? "" : _Espacio.Email;
                    FrecuenciaDTO frecuencia  = CRUDHelper.Read(string.Format("IdentifFrecuencia = '{0}'", miCabecera.IdentifFrecuencia), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.Frecuencia));
                    oSheet.Cells("B15").Value = frecuencia.Name + " de " + _Espacio.HoraInicio + " a " + _Espacio.HoraFin + "hs.";

                    break; }

                case "CERTIFICADO": {

                    EmpresaDTO empresa           = new DAO.EmpresaDAO().Read(1);
                    CertificadoCabDTO miCabecera = (CertificadoCabDTO)_Cabecera;

                    DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));
                    string[] Meses         = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                    string aniomes         = miCabecera.AnoMes.ToString();


                    //ARMADO DE CALENDARIO - MEJORAR
                    int mes       = Convert.ToInt32(aniomes.Substring(4, 2));
                    int anio      = Convert.ToInt32(aniomes.Substring(0, 4));
                    int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);

                    string[] DiasSemana = { "", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };
                    int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                    int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);

                    int dia = PrimerDiaMes - PrimerDiaSemana + 2;

                    for (int Filas = 20; Filas <= 40; Filas = Filas + 5)
                    {
                        for (int Columnas = 2; Columnas <= 8; Columnas++)
                        {

                            DateTime theDate = new DateTime(anio, 1, 1).AddDays(dia - 2);

                            oSheet.Cell(Filas, Columnas).Value = theDate;

                            dia++;
                        }
                    }

                    oSheet.Cells("C5").Value = "Orden de Publicidad - " + miCabecera.IdentifEspacio;
                    oSheet.Cells("B9").Value = miCabecera.PautaId;
                    oSheet.Cells("B10").Value = medio.Name;
                    oSheet.Cells("B11").Value = _Espacio.Name;
                    oSheet.Cells("B12").Value = "'" + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);
                    oSheet.Cells("B13").Value = _Espacio.Contacto == null ? "" : _Espacio.Contacto.ToUpper();
                    oSheet.Cells("A14").Value = "EMAIL: ";
                    oSheet.Cells("B14").Value = _Espacio.Email == null ? "" : _Espacio.Email;
                    FrecuenciaDTO frecuencia = CRUDHelper.Read(string.Format("IdentifFrecuencia = '{0}'", miCabecera.IdentifFrecuencia), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.Frecuencia));
                    oSheet.Cells("B15").Value = frecuencia.Name + " de " + _Espacio.HoraInicio + " a " + _Espacio.HoraFin + "hs.";
                    
                    break; }
            }

            oWB.SaveAs(nomarchivo);
            oWB.Dispose();
            oSheet = null;
            oWB = null;
            GC.Collect(); 

        }
        public void Detalle_OP_Calendario_Descriptivo(string nomArchivo)
        {
            ////// ClosedXML ////////
            XLWorkbook oWB = new XLWorkbook(nomArchivo);
            var oSheet = oWB.Worksheet(1);

            switch (_Estado.ToUpper())
            {
                #region Ordenado
                case "ORDENADO":
                    {

                        OrdenadoCabDTO miCabecera = (OrdenadoCabDTO)_Cabecera;
                        List<OrdenadoDetDTO> miDetalle = (List<OrdenadoDetDTO>)_Detalle;

                        miDetalle = miDetalle.OrderBy(P => P.Dia).ThenBy(Q => Q.Hora).ThenBy(R => R.Salida).ToList();

                        DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));

                        string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                        string[] DiasSemana = { "", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };

                        AvisosDTO aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", miDetalle[0].IdentifAviso));

                        var dao = BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AvisosIdAten);

                        AvisosIdAtenDTO ident =(AvisosIdAtenDTO)CRUDHelper.Read((string.Format("IdentifAviso = '{0}'", miDetalle[0].IdentifAviso)), dao);

                        dao = BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.IdentAtencion);

                        IdentAtencionDTO entity = (DTO.IdentAtencionDTO)CRUDHelper.Read(ident.RecId, dao);

                        if(entity != null)
                        {
                            oSheet.Cells("D16").Value = "Teléfonos " + entity.Telefono;
                        }

                        string aniomes = miCabecera.AnoMes.ToString();

                        List<string> IdentifAvisos = new List<string>();

                        for (int i = 0; i <= miDetalle.Count - 1; i++)
                        {

                            if (IdentifAvisos.Count == 0)
                            {
                                IdentifAvisos.Add(miDetalle[i].IdentifAviso);
                            }

                            bool lencontrado = false;

                            string scadena = miDetalle[i].IdentifAviso;

                            for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                            {
                                if (IdentifAvisos[j] == scadena)
                                {
                                    lencontrado = true;

                                    break;
                                }
                            }

                            if (!lencontrado)
                            {
                                IdentifAvisos.Add(miDetalle[i].IdentifAviso);

                                break;
                            }

                        }

                        List<string> Horarios = new List<string>();

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            int cantsal = 0;

                            for (int j = 0; j <= miDetalle.Count - 1; j++)
                            {
                                if (miDetalle[j].IdentifAviso == IdentifAvisos[i])
                                {
                                    cantsal++;

                                }

                            }
                        }

                        Horarios.Add("");

                        string sHora = string.Empty;

                        for (int i = 0; i <= miDetalle.Count - 1; i++)
                        {
                            sHora = miDetalle[i].Hora.ToString();

                            bool lEncontrado = false;

                            for (int j = 0; j <= Horarios.Count - 1; j++)
                            {
                                if (Horarios[j] == miDetalle[i].Hora.ToString())
                                {
                                    lEncontrado = true;

                                    break;
                                }
                            }

                            if (!lEncontrado)
                            {
                                Horarios.Add(miDetalle[i].Hora.ToString());
                            }
                        }

                        Horarios.RemoveAt(0);

                        Horarios.Sort();

                        string[] Celdas = { "", "", "B", "C", "D", "E", "F", "G", "H" };

                        if (Horarios.Count > 1)
                        {
                            oSheet.Row(41).InsertRowsBelow(Horarios.Count - 1);
                            oSheet.Row(36).InsertRowsBelow(Horarios.Count - 1);
                            oSheet.Row(31).InsertRowsBelow(Horarios.Count - 1);
                            oSheet.Row(26).InsertRowsBelow(Horarios.Count - 1);
                            oSheet.Row(21).InsertRowsBelow(Horarios.Count - 1);

                        }

                        int FilaBase = 21;

                        for (int j = 1; j <= 5; j++) //semanas
                        {

                            for (int k = 2; k <= 8; k++) //columnas
                            {
                                oSheet.Cell(FilaBase + Horarios.Count, k).FormulaA1 = string.Format("=COUNTA({0}{1}:{2}{3})", Celdas[k].ToString(), (FilaBase).ToString(), Celdas[k].ToString(), (FilaBase + Horarios.Count - 1).ToString());
                            }

                            FilaBase += 5 + Horarios.Count - 1;

                        }

                        int anio = Convert.ToInt32(miCabecera.AnoMes.ToString().Substring(0, 4));
                        int mes = Convert.ToInt32(miCabecera.AnoMes.ToString().Substring(4, 2));

                        int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);

                        for (int x = 0; x <= 4; x++)
                        {
                            FilaBase = 20 + (5 * x);

                            FilaBase += ((Horarios.Count - 1) * x) + 1;

                            for (int i = 0; i <= Horarios.Count - 1; i++)
                            {
                                oSheet.Cell(FilaBase + i, 1).Value = Horarios[i].ToString();

                            }

                            for (int i = 2; i <= 8; i++)
                            {
                                string DiaAnio = oSheet.Cell(FilaBase - 1, i).Value.ToString();

                                for (int j = 0; j <= miDetalle.Count - 1; j++)
                                {
                                    if (miDetalle[j].Fecha.ToString() == DiaAnio)
                                    {
                                        for (int k = 0; k <= Horarios.Count - 1; k++)
                                        {
                                            if (miDetalle[j].Hora.ToString() == oSheet.Cell(FilaBase + k, 1).Value.ToString())
                                            {
                                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", miDetalle[j].IdentifAviso));

                                                oSheet.Cell(FilaBase + k, i).Value = aviso.EtiquetaProd;

                                                break;

                                            }
                                        }
                                    }
                                }
                            }

                            decimal CosOp = 0;

                            for (int i = 0; i <= miDetalle.Count - 1; i++)
                            {
                                CosOp += miDetalle[i].CostoOp;
                            }

                            int CeldaCosOp = 48 + ((Horarios.Count - 1) * 5);

                            oSheet.Cells("H" + CeldaCosOp.ToString()).Value = CosOp;


                            ////firma//
                            oSheet.Cells("H" + (CeldaCosOp + 5).ToString()).Value = _Espacio.Responsable;

                            DAO.SetUpDAO STUP = new DAO.SetUpDAO();
                            SetUpDTO setup = STUP.Read(1);
                            oSheet.Cells("H" + (CeldaCosOp + 6).ToString()).Value = setup.Sector;

                            EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);
                            oSheet.Cells("H" + (CeldaCosOp + 7).ToString()).Value = empresa.Name;

                            oSheet.Name = "O" + aniomes + miCabecera.IdentifEspacio;


                        }

                        break;
                    }
                #endregion
                #region Estimado
                case "ESTIMADO":
                    {

                        EstimadoCabDTO miCabecera = (EstimadoCabDTO)_Cabecera;
                        List<EstimadoDetDTO> miDetalle = (List<EstimadoDetDTO>)_Detalle;

                        miDetalle = miDetalle.OrderBy(P => P.Dia).ThenBy(Q => Q.Hora).ThenBy(R => R.Salida).ToList();

                        DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));

                        string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                        string[] DiasSemana = { "", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };

                        AvisosDTO aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", miDetalle[0].IdentifAviso));

                        var dao = BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AvisosIdAten);

                        AvisosIdAtenDTO ident =(AvisosIdAtenDTO)CRUDHelper.Read((string.Format("IdentifAviso = '{0}'", miDetalle[0].IdentifAviso)), dao);

                        dao = BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.IdentAtencion);

                        IdentAtencionDTO entity = (DTO.IdentAtencionDTO)CRUDHelper.Read(ident.RecId, dao);

                        if(entity != null)
                        {
                            oSheet.Cells("D16").Value = "Teléfonos " + entity.Telefono;
                        }

                        string aniomes = miCabecera.AnoMes.ToString();

                        List<string> IdentifAvisos = new List<string>();

                        for (int i = 0; i <= miDetalle.Count - 1; i++)
                        {

                            if (IdentifAvisos.Count == 0)
                            {
                                IdentifAvisos.Add(miDetalle[i].IdentifAviso);
                            }

                            bool lencontrado = false;

                            string scadena = miDetalle[i].IdentifAviso;

                            for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                            {
                                if (IdentifAvisos[j] == scadena)
                                {
                                    lencontrado = true;

                                    break;
                                }
                            }

                            if (!lencontrado)
                            {
                                IdentifAvisos.Add(miDetalle[i].IdentifAviso);

                                break;
                            }

                        }

                        List<string> Horarios = new List<string>();

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            int cantsal = 0;

                            for (int j = 0; j <= miDetalle.Count - 1; j++)
                            {
                                if (miDetalle[j].IdentifAviso == IdentifAvisos[i])
                                {
                                    cantsal++;

                                }

                            }
                        }

                        Horarios.Add("");

                        string sHora = string.Empty;

                        for (int i = 0; i <= miDetalle.Count - 1; i++)
                        {
                            sHora = miDetalle[i].Hora.ToString();

                            bool lEncontrado = false;

                            for (int j = 0; j <= Horarios.Count - 1; j++)
                            {
                                if (Horarios[j] == miDetalle[i].Hora.ToString())
                                {
                                    lEncontrado = true;

                                    break;
                                }
                            }

                            if (!lEncontrado)
                            {
                                Horarios.Add(miDetalle[i].Hora.ToString());
                            }
                        }

                        Horarios.RemoveAt(0);

                        Horarios.Sort();

                        string[] Celdas = { "", "", "B", "C", "D", "E", "F", "G", "H" };

                        if (Horarios.Count > 1)
                        {
                            oSheet.Row(41).InsertRowsBelow(Horarios.Count - 1);
                            oSheet.Row(36).InsertRowsBelow(Horarios.Count - 1);
                            oSheet.Row(31).InsertRowsBelow(Horarios.Count - 1);
                            oSheet.Row(26).InsertRowsBelow(Horarios.Count - 1);
                            oSheet.Row(21).InsertRowsBelow(Horarios.Count - 1);

                        }

                        int FilaBase = 21;

                        for (int j = 1; j <= 5; j++) //semanas
                        {

                            for (int k = 2; k <= 8; k++) //columnas
                            {
                                oSheet.Cell(FilaBase + Horarios.Count, k).FormulaA1 = string.Format("=COUNTA({0}{1}:{2}{3})", Celdas[k].ToString(), (FilaBase).ToString(), Celdas[k].ToString(), (FilaBase + Horarios.Count - 1).ToString());
                            }

                            FilaBase += 5 + Horarios.Count - 1;

                        }

                        int anio = Convert.ToInt32(miCabecera.AnoMes.ToString().Substring(0, 4));
                        int mes = Convert.ToInt32(miCabecera.AnoMes.ToString().Substring(4, 2));

                        int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);

                        for (int x = 0; x <= 4; x++)
                        {
                            FilaBase = 20 + (5 * x);

                            FilaBase += ((Horarios.Count - 1) * x) + 1;

                            for (int i = 0; i <= Horarios.Count - 1; i++)
                            {
                                oSheet.Cell(FilaBase + i, 1).Value = Horarios[i].ToString();

                            }

                            for (int i = 2; i <= 8; i++)
                            {
                                string DiaAnio = oSheet.Cell(FilaBase - 1, i).Value.ToString();

                                for (int j = 0; j <= miDetalle.Count - 1; j++)
                                {
                                    if (miDetalle[j].Fecha.ToString() == DiaAnio)
                                    {
                                        for (int k = 0; k <= Horarios.Count - 1; k++)
                                        {
                                            if (miDetalle[j].Hora.ToString() == oSheet.Cell(FilaBase + k, 1).Value.ToString())
                                            {
                                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", miDetalle[j].IdentifAviso));

                                                oSheet.Cell(FilaBase + k, i).Value = aviso.EtiquetaProd;

                                                break;

                                            }
                                        }
                                    }
                                }
                            }

                            decimal CosOp = 0;

                            for (int i = 0; i <= miDetalle.Count - 1; i++)
                            {
                                CosOp += miDetalle[i].CostoOp;
                            }

                            int CeldaCosOp = 48 + ((Horarios.Count - 1) * 5);

                            oSheet.Cells("H" + CeldaCosOp.ToString()).Value = CosOp;


                            ////firma//
                            oSheet.Cells("H" + (CeldaCosOp + 5).ToString()).Value = _Espacio.Responsable;

                            DAO.SetUpDAO STUP = new DAO.SetUpDAO();
                            SetUpDTO setup = STUP.Read(1);
                            oSheet.Cells("H" + (CeldaCosOp + 6).ToString()).Value = setup.Sector;

                            EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);
                            oSheet.Cells("H" + (CeldaCosOp + 7).ToString()).Value = empresa.Name;

                            oSheet.Name = "O" + aniomes + miCabecera.IdentifEspacio;


                        }

                        break;
                    }
                #endregion
                #region Certificado
                case "CERTIFICADO":
                    {
                        CertificadoCabDTO miCabecera = (CertificadoCabDTO)_Cabecera;
                        List<CertificadoDetDTO> miDetalle = (List<CertificadoDetDTO>)_Detalle;

                        miDetalle = miDetalle.OrderBy(P => P.Dia).ThenBy(Q => Q.Hora).ThenBy(R => R.Salida).ToList();

                        DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));

                        string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                        string[] DiasSemana = { "", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };

                        AvisosDTO aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", miDetalle[0].IdentifAviso));

                        var dao = BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AvisosIdAten);

                        AvisosIdAtenDTO ident = (AvisosIdAtenDTO)CRUDHelper.Read((string.Format("IdentifAviso = '{0}'", miDetalle[0].IdentifAviso)), dao);

                        dao = BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.IdentAtencion);

                        IdentAtencionDTO entity = (DTO.IdentAtencionDTO)CRUDHelper.Read(ident.RecId, dao);

                        if (entity != null)
                        {
                            oSheet.Cells("D16").Value = "Teléfonos " + entity.Telefono;
                        }

                        string aniomes = miCabecera.AnoMes.ToString();

                        List<string> IdentifAvisos = new List<string>();

                        for (int i = 0; i <= miDetalle.Count - 1; i++)
                        {

                            if (IdentifAvisos.Count == 0)
                            {
                                IdentifAvisos.Add(miDetalle[i].IdentifAviso);
                            }

                            bool lencontrado = false;

                            string scadena = miDetalle[i].IdentifAviso;

                            for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                            {
                                if (IdentifAvisos[j] == scadena)
                                {
                                    lencontrado = true;

                                    break;
                                }
                            }

                            if (!lencontrado)
                            {
                                IdentifAvisos.Add(miDetalle[i].IdentifAviso);

                                break;
                            }

                        }

                        List<string> Horarios = new List<string>();

                        for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                        {
                            int cantsal = 0;

                            for (int j = 0; j <= miDetalle.Count - 1; j++)
                            {
                                if (miDetalle[j].IdentifAviso == IdentifAvisos[i])
                                {
                                    cantsal++;

                                }

                            }
                        }

                        Horarios.Add("");

                        string sHora = string.Empty;

                        for (int i = 0; i <= miDetalle.Count - 1; i++)
                        {
                            sHora = miDetalle[i].Hora.ToString();

                            bool lEncontrado = false;

                            for (int j = 0; j <= Horarios.Count - 1; j++)
                            {
                                if (Horarios[j] == miDetalle[i].Hora.ToString())
                                {
                                    lEncontrado = true;

                                    break;
                                }
                            }

                            if (!lEncontrado)
                            {
                                Horarios.Add(miDetalle[i].Hora.ToString());
                            }
                        }

                        Horarios.RemoveAt(0);

                        Horarios.Sort();

                        string[] Celdas = { "", "", "B", "C", "D", "E", "F", "G", "H" };

                        if (Horarios.Count > 1)
                        {
                            oSheet.Row(41).InsertRowsBelow(Horarios.Count - 1);
                            oSheet.Row(36).InsertRowsBelow(Horarios.Count - 1);
                            oSheet.Row(31).InsertRowsBelow(Horarios.Count - 1);
                            oSheet.Row(26).InsertRowsBelow(Horarios.Count - 1);
                            oSheet.Row(21).InsertRowsBelow(Horarios.Count - 1);

                        }

                        int FilaBase = 21;

                        for (int j = 1; j <= 5; j++) //semanas
                        {

                            for (int k = 2; k <= 8; k++) //columnas
                            {
                                oSheet.Cell(FilaBase + Horarios.Count, k).FormulaA1 = string.Format("=COUNTA({0}{1}:{2}{3})", Celdas[k].ToString(), (FilaBase).ToString(), Celdas[k].ToString(), (FilaBase + Horarios.Count - 1).ToString());
                            }

                            FilaBase += 5 + Horarios.Count - 1;

                        }

                        int anio = Convert.ToInt32(miCabecera.AnoMes.ToString().Substring(0, 4));
                        int mes = Convert.ToInt32(miCabecera.AnoMes.ToString().Substring(4, 2));

                        int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);

                        for (int x = 0; x <= 4; x++)
                        {
                            FilaBase = 20 + (5 * x);

                            FilaBase += ((Horarios.Count - 1) * x) + 1;

                            for (int i = 0; i <= Horarios.Count - 1; i++)
                            {
                                oSheet.Cell(FilaBase + i, 1).Value = Horarios[i].ToString();

                            }

                            for (int i = 2; i <= 8; i++)
                            {
                                string DiaAnio = oSheet.Cell(FilaBase - 1, i).Value.ToString();

                                for (int j = 0; j <= miDetalle.Count - 1; j++)
                                {
                                    if (miDetalle[j].Fecha.ToString() == DiaAnio)
                                    {
                                        for (int k = 0; k <= Horarios.Count - 1; k++)
                                        {
                                            if (miDetalle[j].Hora.ToString() == oSheet.Cell(FilaBase + k, 1).Value.ToString())
                                            {
                                                aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", miDetalle[j].IdentifAviso));

                                                oSheet.Cell(FilaBase + k, i).Value = aviso.EtiquetaProd;

                                                break;

                                            }
                                        }
                                    }
                                }
                            }

                            decimal CosOp = 0;

                            for (int i = 0; i <= miDetalle.Count - 1; i++)
                            {
                                CosOp += miDetalle[i].CostoOp;
                            }

                            int CeldaCosOp = 48 + ((Horarios.Count - 1) * 5);

                            oSheet.Cells("H" + CeldaCosOp.ToString()).Value = CosOp;


                            ////firma//
                            oSheet.Cells("H" + (CeldaCosOp + 5).ToString()).Value = _Espacio.Responsable;

                            DAO.SetUpDAO STUP = new DAO.SetUpDAO();
                            SetUpDTO setup = STUP.Read(1);
                            oSheet.Cells("H" + (CeldaCosOp + 6).ToString()).Value = setup.Sector;

                            EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);
                            oSheet.Cells("H" + (CeldaCosOp + 7).ToString()).Value = empresa.Name;

                            oSheet.Name = "O" + aniomes + miCabecera.IdentifEspacio;


                        }

                        break;
                    }

                #endregion
            }

            oWB.SaveAs(nomArchivo);
            oWB.Dispose();
            oSheet = null;
            oWB = null;
            GC.Collect();
        }
        /// <summary>
        /// Exports the excel event handler.
        /// </summary>
        /// <param name="context">The context.</param>
        private void ExportExcelEventHandler(ControllerContext context)
        {
            try
            {
                var workbook = new XLWorkbook();

                if (this.ExportData != null)
                {
                    context.HttpContext.Response.Clear();

                    // 編碼
                    context.HttpContext.Response.ContentEncoding = Encoding.UTF8;

                    // 設定網頁ContentType
                    context.HttpContext.Response.ContentType =
                        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

                    // 匯出檔名
                    var browser = context.HttpContext.Request.Browser.Browser;
                    var exportFileName = browser.Equals("Firefox", StringComparison.OrdinalIgnoreCase)
                        ? this.FileName
                        : HttpUtility.UrlEncode(this.FileName, Encoding.UTF8);

                    context.HttpContext.Response.AddHeader(
                        "Content-Disposition",
                        string.Format("attachment;filename={0}", exportFileName));

                    // Add all DataTables in the DataSet as a worksheets
                    workbook.Worksheets.Add(this.ExportData, this.SheetName);

                    using (var memoryStream = new MemoryStream())
                    {
                        workbook.SaveAs(memoryStream);
                        memoryStream.WriteTo(context.HttpContext.Response.OutputStream);
                        memoryStream.Close();
                    }
                }
                workbook.Dispose();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public void Detalle_OP_Grafica(string nomArchivo)
        {

            ////// ClosedXML ////////
            XLWorkbook oWB = new XLWorkbook(nomArchivo);
            var oSheet = oWB.Worksheet(1);

            switch (_Estado.ToUpper())
            {
                case "ORDENADO": 
                    {
                        OrdenadoCabDTO miCabecera = (OrdenadoCabDTO)_Cabecera;
                        List<OrdenadoDetDTO> miDetalle = (List<OrdenadoDetDTO>)_Detalle;
                        miDetalle = miDetalle.OrderBy(P => P.Dia).ThenBy(Q => Q.Hora).ThenBy(R => R.Salida).ToList();

                        int Fila = 18;

                        if (miDetalle.Count > 1)
                        {
                            for (int i = 1; i <= miDetalle.Count - 1; i++)
                            {
                               var rng = oSheet.Range("B" + Fila.ToString() + ":G" + (Fila).ToString());
                               rng.InsertRowsBelow(3);

                            }
                        }

                        Fila = 19;

                        for (int i = 1; i <= miDetalle.Count - 1; i++)
                        {
                            var xlSourceRange = oSheet.Range("B16:G17");

                            oSheet.Cell(Fila,2).Value = xlSourceRange;

                            Fila = Fila + 3;
                        }

                        Fila = 14;

                        decimal SubTotal = 0;

                        for (int i = 0; i <= miDetalle.Count - 1; i++)
                        {
                            Fila += 3;

                            AvisosDTO aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", miDetalle[i].IdentifAviso));
                            DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));
                            oSheet.Cell(Fila, 2).Value = medio.Name;
                            oSheet.Cell(Fila, 3).Value = _Espacio.Name;
                            oSheet.Cell(Fila, 4).Value = aviso.EtiquetaProd;
                            FormAvisoDTO formaviso = Business.CRUDHelper.Read(string.Format("IdentifFormAviso = '{0}'", aviso.IdentifFormAviso), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.FormAviso));
                            oSheet.Cell(Fila, 5).Value = formaviso.Name;
                            oSheet.Cell(Fila, 6).Value = miDetalle[i].Dia.ToString("00") +"/" + miCabecera.AnoMes.ToString("00").Substring(4, 2) + "/" + miCabecera.AnoMes.ToString().Substring(0, 4);
                            oSheet.Cell(Fila, 7).Value = miDetalle[i].CostoOp;

                            SubTotal += miDetalle[i].CostoOp;

                        }

                        Fila += 2;
                        oSheet.Cell(Fila, 7).Value = SubTotal;

                        Fila += 6;

                        oSheet.Cell(Fila, 6).Value = _Espacio.Responsable;

                        DAO.SetUpDAO STUP = new DAO.SetUpDAO();

                        SetUpDTO setup = STUP.Read(1);

                        string sector = setup.Sector;

                        oSheet.Cell(Fila + 1, 6).Value = sector;

                        oSheet.Style.Alignment.SetShrinkToFit();

                        var Cols = oSheet.Columns();
                        var Rows = oSheet.Rows();

                        foreach (IXLRow fila in Rows)
                        {
                            fila.AdjustToContents();
                        }

                        foreach( IXLColumn columna in Cols)
                        {
                            columna.AdjustToContents();
                            
                        }

                    break; 

                    }
                case "ESTIMADO": 
                    {

                        EstimadoCabDTO miCabecera = (EstimadoCabDTO)_Cabecera;
                        List<EstimadoDetDTO> miDetalle = (List<EstimadoDetDTO>)_Detalle;
                        miDetalle = miDetalle.OrderBy(P => P.Dia).ThenBy(Q => Q.Hora).ThenBy(R => R.Salida).ToList();

                        int Fila = 18;

                        if (miDetalle.Count > 1)
                        {
                            for (int i = 1; i <= miDetalle.Count - 1; i++)
                            {
                                var rng = oSheet.Range("B" + Fila.ToString() + ":G" + (Fila).ToString());
                                rng.InsertRowsBelow(3);

                            }
                        }

                        Fila = 19;

                        for (int i = 1; i <= miDetalle.Count - 1; i++)
                        {
                            var xlSourceRange = oSheet.Range("B16:G17");

                            oSheet.Cell(Fila, 2).Value = xlSourceRange;

                            Fila = Fila + 3;
                        }

                        Fila = 14;

                        decimal SubTotal = 0;

                        for (int i = 0; i <= miDetalle.Count - 1; i++)
                        {
                            Fila += 3;

                            AvisosDTO aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", miDetalle[i].IdentifAviso));
                            DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));
                            oSheet.Cell(Fila, 2).Value = medio.Name;
                            oSheet.Cell(Fila, 3).Value = _Espacio.Name;
                            oSheet.Cell(Fila, 4).Value = aviso.EtiquetaProd;
                            FormAvisoDTO formaviso = Business.CRUDHelper.Read(string.Format("IdentifFormAviso = '{0}'", aviso.IdentifFormAviso), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.FormAviso));
                            oSheet.Cell(Fila, 5).Value = formaviso.Name;
                            oSheet.Cell(Fila, 6).Value = miDetalle[i].Dia.ToString("00") + "/" + miCabecera.AnoMes.ToString("00").Substring(4, 2) + "/" + miCabecera.AnoMes.ToString().Substring(0, 4);
                            oSheet.Cell(Fila, 7).Value = miDetalle[i].CostoOp;

                            SubTotal += miDetalle[i].CostoOp;

                        }

                        Fila += 2;
                        oSheet.Cell(Fila, 7).Value = SubTotal;

                        Fila += 6;

                        oSheet.Cell(Fila, 6).Value = _Espacio.Responsable;

                        DAO.SetUpDAO STUP = new DAO.SetUpDAO();

                        SetUpDTO setup = STUP.Read(1);

                        string sector = setup.Sector;

                        oSheet.Cell(Fila + 1, 6).Value = sector;

                        oSheet.Style.Alignment.SetShrinkToFit();

                        var Cols = oSheet.Columns();
                        var Rows = oSheet.Rows();

                        foreach (IXLRow fila in Rows)
                        {
                            fila.AdjustToContents();
                        }

                        foreach (IXLColumn columna in Cols)
                        {
                            columna.AdjustToContents();

                        }

                        break;
                    }
                case "CERTIFICADO": 
                    {

                        CertificadoCabDTO miCabecera = (CertificadoCabDTO)_Cabecera;
                        List<CertificadoDetDTO> miDetalle = (List<CertificadoDetDTO>)_Detalle;
                        miDetalle = miDetalle.OrderBy(P => P.Dia).ThenBy(Q => Q.Hora).ThenBy(R => R.Salida).ToList();

                        int Fila = 18;

                        if (miDetalle.Count > 1)
                        {
                            for (int i = 1; i <= miDetalle.Count - 1; i++)
                            {
                                var rng = oSheet.Range("B" + Fila.ToString() + ":G" + (Fila).ToString());
                                rng.InsertRowsBelow(3);

                            }
                        }

                        Fila = 19;

                        for (int i = 1; i <= miDetalle.Count - 1; i++)
                        {
                            var xlSourceRange = oSheet.Range("B16:G17");

                            oSheet.Cell(Fila, 2).Value = xlSourceRange;

                            Fila = Fila + 3;
                        }

                        Fila = 14;

                        decimal SubTotal = 0;

                        for (int i = 0; i <= miDetalle.Count - 1; i++)
                        {
                            Fila += 3;

                            AvisosDTO aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", miDetalle[i].IdentifAviso));
                            DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));
                            oSheet.Cell(Fila, 2).Value = medio.Name;
                            oSheet.Cell(Fila, 3).Value = _Espacio.Name;
                            oSheet.Cell(Fila, 4).Value = aviso.EtiquetaProd;
                            FormAvisoDTO formaviso = Business.CRUDHelper.Read(string.Format("IdentifFormAviso = '{0}'", aviso.IdentifFormAviso), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.FormAviso));
                            oSheet.Cell(Fila, 5).Value = formaviso.Name;
                            oSheet.Cell(Fila, 6).Value = miDetalle[i].Dia.ToString("00") + "/" + miCabecera.AnoMes.ToString("00").Substring(4, 2) + "/" + miCabecera.AnoMes.ToString().Substring(0, 4);
                            oSheet.Cell(Fila, 7).Value = miDetalle[i].CostoOp;

                            SubTotal += miDetalle[i].CostoOp;

                        }

                        Fila += 2;
                        oSheet.Cell(Fila, 7).Value = SubTotal;

                        Fila += 6;

                        oSheet.Cell(Fila, 6).Value = _Espacio.Responsable;

                        DAO.SetUpDAO STUP = new DAO.SetUpDAO();

                        SetUpDTO setup = STUP.Read(1);

                        string sector = setup.Sector;

                        oSheet.Cell(Fila + 1, 6).Value = sector;

                        oSheet.Style.Alignment.SetShrinkToFit();

                        var Cols = oSheet.Columns();
                        var Rows = oSheet.Rows();

                        foreach (IXLRow fila in Rows)
                        {
                            fila.AdjustToContents();
                        }

                        foreach (IXLColumn columna in Cols)
                        {
                            columna.AdjustToContents();

                        }

                        break;

                    }
            }


            oWB.SaveAs(nomArchivo);
            oWB.Dispose();
            oSheet = null;
            oWB = null;
            GC.Collect(); 
        
        }
Example #24
0
		private void WriteOutStatusTaggedGenderExcel
			(WordUp.DataSelection dataSelection, string outputFileName)
			{
			XLWorkbook workBook = new XLWorkbook();
			IXLWorksheet dataSelectionWorkSheet = workBook.Worksheets.Add($"{dataSelection}");
			workBook.SaveAs(new FileStream(outputFileName, FileMode.Create,
				FileAccess.Write, FileShare.ReadWrite));
			workBook.Dispose();
			}
        public void Detalle_OP_PNT_Producto(string nomarchivo)
        {

            ////// ClosedXML ////////
            XLWorkbook oWB = new XLWorkbook(nomarchivo);
            var oSheet = oWB.Worksheet(1);

            switch (_Estado.ToUpper())
            {
                case "ORDENADO": { 

                    OrdenadoCabDTO miCabecera = (OrdenadoCabDTO)_Cabecera;
                    List<OrdenadoDetDTO> miDetalle = (List<OrdenadoDetDTO>)_Detalle;
                    miDetalle = miDetalle.OrderBy(P => P.Dia).ThenBy(Q => Q.Hora).ThenBy(R => R.Salida).ToList();

                    string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                    string[] DiasSemana = { "", "L", "M", "M", "J", "V", "S", "D" };

                    AvisosDTO aviso = null;

                    string aniomes = miCabecera.AnoMes.ToString();
                    int mes = Convert.ToInt32(aniomes.Substring(4, 2));
                    int anio = Convert.ToInt32(aniomes.Substring(0, 4));
                    int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);
                    int[] DiasPautados = new int[DiasEnMes + 1];
                    int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                    int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);
                    int dia = PrimerDiaMes - PrimerDiaSemana + 2;
                    int DiaDelAnio = miDetalle[0].Fecha.DayOfYear;

                    //ARMADO DE CALENDARIO - MEJORAR

                    for (int x = 1; x <= DiasEnMes; x++)
                    {
                        for (int j = 0; j <= miDetalle.Count - 1; j++)
                        {
                            if (miDetalle[j].Fecha.Day == x)
                            {
                                DiasPautados[x]++;
                            }
                        }
                    }

                    int iDia = PrimerDiaSemana;
                    //LIMPIEZA DE DIAS Y FECHAS
                    for (int i = 1; i <= 31; i++)
                    {
                        oSheet.Cell(19, 6 + i).Value = "";
                        oSheet.Cell(20, 6 + i).Value = "";
                    }

                    iDia = PrimerDiaSemana;
            
                    for (int i = 1; i <= DiasEnMes; i++)
                    {

                        oSheet.Cell(19, 6 + i).Value = DiasSemana[iDia].ToUpper();
                        oSheet.Cell(20, 6 + i).Value = i;

                        if (oSheet.Cell(19, 6 + i).Value.ToString() == "S" || oSheet.Cell(19, 6 + i).Value.ToString() == "D")
                        {
                            for (int x = 21; x <= 25; x++)
                            {
                                Color color = Color.FromArgb(66, 66, 66);
                                //oSheet.Cell(x, 6 + i)].interior.color = color;
                            }
                        }
                        else
                        {
                            for (int x = 21; x <= 25; x++)
                            {
                                Color color = Color.FromArgb(128, 128, 128);
                                //oSheet.Cell(x, 6 + i).interior.color = color;
                            }
                        }

                        iDia++;

                        if (iDia == 8)
                        {
                            iDia = 1;
                        }
                    }

                    //CALCULA LA MAXIMA CANTIDAD DE SALIDAS DE AVISOS
                    int MaxLines = 0;

                    for (int k = 0; k <= DiasPautados.Length - 1; k++)
                    {
                        if (DiasPautados[k] > MaxLines)
                        {
                            MaxLines = DiasPautados[k];
                        }
                    }

                    oSheet.Cell(22, 2).Value = _Espacio.Name;

                    List<string> IdentifAvisos = new List<string>();

                    for (int i = 0; i <= miDetalle.Count - 1; i++)
                    {

                        if (IdentifAvisos.Count == 0)
                        {
                            IdentifAvisos.Add(miDetalle[i].IdentifAviso);
                        }

                        bool lencontrado = false;

                        string scadena = miDetalle[i].IdentifAviso;

                        for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                        {
                            if (IdentifAvisos[j] == scadena)
                            {
                                lencontrado = true;

                                break;
                            }
                        }

                        if (!lencontrado)
                        {
                            IdentifAvisos.Add(miDetalle[i].IdentifAviso);

                            break;
                        }
                    }

                    int Fila = 21;

                    for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                    {
                        aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[i]));

                        DTO.PiezasArteDTO pieza = CRUDHelper.Read(string.Format("IdentifPieza = '{0}'", aviso.IdentifPieza),
                                                    BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.PiezasArte));

                        DTO.AnunInternosDTO ai = CRUDHelper.Read(string.Format("IdentifAnun = '{0}'", pieza.IdentifAnun),
                                                        BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AnunInternos));

                        oSheet.Cell(Fila + i, 3).Value = aviso.EtiquetaProd.ToUpper();
                        oSheet.Cell(Fila + i, 4).Value = ai.Name.ToUpper();
                        oSheet.Cell(Fila + i, 6).Value = aviso.Duracion.ToString() + " SEG.";

                        oSheet.Cell(35 + i, 3).Value = aviso.EtiquetaProd.ToUpper();
                        oSheet.Cell(35 + i, 4).Value = ai.Name;
                        oSheet.Cell(35 + i, 5).Value = aviso.Zocalo;
                        oSheet.Cell(35 + i, 6).Value = aviso.NroIngesta;

                        AvisosIdAtenDTO aia = CRUDHelper.Read(string.Format("IdentifAviso = '{0}'",IdentifAvisos[i]), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AvisosIdAten));

                        oSheet.Cell("D" + (30 + i).ToString()).Value = aia.IdentifIdentAte;
                        
                        int cantsal = 0;

                        decimal CosOp = 0;

                        for (int j = 0; j <= miDetalle.Count - 1; j++)
                        {
                            if (miDetalle[j].IdentifAviso == IdentifAvisos[i])
                            {

                                int ThisDay = (int)miDetalle[j].Dia;
                                int ocurrencias = 0;

                                for (int k = 0; k <= miDetalle.Count - 1; k++)
                                {
                                    if ((int)miDetalle[k].Dia == ThisDay && miDetalle[k].IdentifAviso == IdentifAvisos[i])
                                    {
                                        ocurrencias++;
                                    }
                                }

                                CosOp = miDetalle[j].CostoOp;

                                oSheet.Cell(Fila + i, 6 + ThisDay).Value = ocurrencias;

                                cantsal++;

                            }

                        }

                        oSheet.Cell(Fila + i, 39).Value = CosOp;

                    }

                    oSheet.Name = _Estado.Substring(0, 1).ToUpper() + aniomes + miCabecera.IdentifEspacio;

                   break;
                };

                case "ESTIMADO":{

                    EstimadoCabDTO miCabecera = (EstimadoCabDTO)_Cabecera;
                    List<EstimadoDetDTO> miDetalle = (List<EstimadoDetDTO>)_Detalle;
                    miDetalle = miDetalle.OrderBy(P => P.Dia).ThenBy(Q => Q.Hora).ThenBy(R => R.Salida).ToList();

                    string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                    string[] DiasSemana = { "", "L", "M", "M", "J", "V", "S", "D" };

                    AvisosDTO aviso = null;

                    string aniomes = miCabecera.AnoMes.ToString();
                    int mes = Convert.ToInt32(aniomes.Substring(4, 2));
                    int anio = Convert.ToInt32(aniomes.Substring(0, 4));
                    int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);
                    int[] DiasPautados = new int[DiasEnMes + 1];
                    int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                    int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);
                    int dia = PrimerDiaMes - PrimerDiaSemana + 2;
                    int DiaDelAnio = miDetalle[0].Fecha.DayOfYear;

                    //ARMADO DE CALENDARIO - MEJORAR

                    for (int x = 1; x <= DiasEnMes; x++)
                    {
                        for (int j = 0; j <= miDetalle.Count - 1; j++)
                        {
                            if (miDetalle[j].Fecha.Day == x)
                            {
                                DiasPautados[x]++;
                            }
                        }
                    }

                    int iDia = PrimerDiaSemana;
                    //LIMPIEZA DE DIAS Y FECHAS
                    for (int i = 1; i <= 31; i++)
                    {
                        oSheet.Cell(19, 6 + i).Value = "";
                        oSheet.Cell(20, 6 + i).Value = "";
                    }

                    iDia = PrimerDiaSemana;
            
                    for (int i = 1; i <= DiasEnMes; i++)
                    {

                        oSheet.Cell(19, 6 + i).Value = DiasSemana[iDia].ToUpper();
                        oSheet.Cell(20, 6 + i).Value = i;

                        if (oSheet.Cell(19, 6 + i).Value.ToString() == "S" || oSheet.Cell(19, 6 + i).Value.ToString() == "D")
                        {
                            for (int x = 21; x <= 25; x++)
                            {
                                Color color = Color.FromArgb(66, 66, 66);
                                //oSheet.Cell(x, 6 + i)].interior.color = color;
                            }
                        }
                        else
                        {
                            for (int x = 21; x <= 25; x++)
                            {
                                Color color = Color.FromArgb(128, 128, 128);
                                //oSheet.Cell(x, 6 + i).interior.color = color;
                            }
                        }

                        iDia++;

                        if (iDia == 8)
                        {
                            iDia = 1;
                        }
                    }

                    //CALCULA LA MAXIMA CANTIDAD DE SALIDAS DE AVISOS
                    int MaxLines = 0;

                    for (int k = 0; k <= DiasPautados.Length - 1; k++)
                    {
                        if (DiasPautados[k] > MaxLines)
                        {
                            MaxLines = DiasPautados[k];
                        }
                    }

                    oSheet.Cell(22, 2).Value = _Espacio.Name;

                    List<string> IdentifAvisos = new List<string>();

                    for (int i = 0; i <= miDetalle.Count - 1; i++)
                    {

                        if (IdentifAvisos.Count == 0)
                        {
                            IdentifAvisos.Add(miDetalle[i].IdentifAviso);
                        }

                        bool lencontrado = false;

                        string scadena = miDetalle[i].IdentifAviso;

                        for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                        {
                            if (IdentifAvisos[j] == scadena)
                            {
                                lencontrado = true;

                                break;
                            }
                        }

                        if (!lencontrado)
                        {
                            IdentifAvisos.Add(miDetalle[i].IdentifAviso);

                            break;
                        }
                    }

                    int Fila = 21;

                    for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                    {
                        aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[i]));

                        DTO.PiezasArteDTO pieza = CRUDHelper.Read(string.Format("IdentifPieza = '{0}'", aviso.IdentifPieza),
                                                    BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.PiezasArte));

                        DTO.AnunInternosDTO ai = CRUDHelper.Read(string.Format("IdentifAnun = '{0}'", pieza.IdentifAnun),
                                                        BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AnunInternos));

                        oSheet.Cell(Fila + i, 3).Value = aviso.EtiquetaProd.ToUpper();
                        oSheet.Cell(Fila + i, 4).Value = ai.Name.ToUpper();
                        oSheet.Cell(Fila + i, 6).Value = aviso.Duracion.ToString() + " SEG.";

                        oSheet.Cell(35 + i, 3).Value = aviso.EtiquetaProd.ToUpper();
                        oSheet.Cell(35 + i, 4).Value = ai.Name;
                        oSheet.Cell(35 + i, 5).Value = aviso.Zocalo;
                        oSheet.Cell(35 + i, 6).Value = aviso.NroIngesta;

                        AvisosIdAtenDTO aia = CRUDHelper.Read(string.Format("IdentifAviso = '{0}'",IdentifAvisos[i]), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AvisosIdAten));

                        oSheet.Cell("D" + (30 + i).ToString()).Value = aia.IdentifIdentAte;
                        
                        int cantsal = 0;

                        decimal CosOp = 0;

                        for (int j = 0; j <= miDetalle.Count - 1; j++)
                        {
                            if (miDetalle[j].IdentifAviso == IdentifAvisos[i])
                            {

                                int ThisDay = (int)miDetalle[j].Dia;
                                int ocurrencias = 0;

                                for (int k = 0; k <= miDetalle.Count - 1; k++)
                                {
                                    if ((int)miDetalle[k].Dia == ThisDay && miDetalle[k].IdentifAviso == IdentifAvisos[i])
                                    {
                                        ocurrencias++;
                                    }
                                }

                                CosOp = miDetalle[j].CostoOp;

                                oSheet.Cell(Fila + i, 6 + ThisDay).Value = ocurrencias;

                                cantsal++;

                            }

                        }

                        oSheet.Cell(Fila + i, 39).Value = CosOp;

                    }

                    oSheet.Name = _Estado.Substring(0, 1).ToUpper() + aniomes + miCabecera.IdentifEspacio;

                   break;
                };
                #endregion
                #region Certificado
                case "CERTIFICADO":{

                    CertificadoCabDTO miCabecera = (CertificadoCabDTO)_Cabecera;
                    List<CertificadoDetDTO> miDetalle = (List<CertificadoDetDTO>)_Detalle;
                    miDetalle = miDetalle.OrderBy(P => P.Dia).ThenBy(Q => Q.Hora).ThenBy(R => R.Salida).ToList();

                    string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                    string[] DiasSemana = { "", "L", "M", "M", "J", "V", "S", "D" };

                    AvisosDTO aviso = null;

                    string aniomes = miCabecera.AnoMes.ToString();
                    int mes = Convert.ToInt32(aniomes.Substring(4, 2));
                    int anio = Convert.ToInt32(aniomes.Substring(0, 4));
                    int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);
                    int[] DiasPautados = new int[DiasEnMes + 1];
                    int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                    int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);
                    int dia = PrimerDiaMes - PrimerDiaSemana + 2;
                    int DiaDelAnio = miDetalle[0].Fecha.DayOfYear;

                    //ARMADO DE CALENDARIO - MEJORAR

                    for (int x = 1; x <= DiasEnMes; x++)
                    {
                        for (int j = 0; j <= miDetalle.Count - 1; j++)
                        {
                            if (miDetalle[j].Fecha.Day == x)
                            {
                                DiasPautados[x]++;
                            }
                        }
                    }

                    int iDia = PrimerDiaSemana;
                    //LIMPIEZA DE DIAS Y FECHAS
                    for (int i = 1; i <= 31; i++)
                    {
                        oSheet.Cell(19, 6 + i).Value = "";
                        oSheet.Cell(20, 6 + i).Value = "";
                    }

                    iDia = PrimerDiaSemana;

                    for (int i = 1; i <= DiasEnMes; i++)
                    {

                        oSheet.Cell(19, 6 + i).Value = DiasSemana[iDia].ToUpper();
                        oSheet.Cell(20, 6 + i).Value = i;

                        if (oSheet.Cell(19, 6 + i).Value.ToString() == "S" || oSheet.Cell(19, 6 + i).Value.ToString() == "D")
                        {
                            for (int x = 21; x <= 25; x++)
                            {
                                Color color = Color.FromArgb(66, 66, 66);
                                //oSheet.Cell(x, 6 + i)].interior.color = color;
                            }
                        }
                        else
                        {
                            for (int x = 21; x <= 25; x++)
                            {
                                Color color = Color.FromArgb(128, 128, 128);
                                //oSheet.Cell(x, 6 + i).interior.color = color;
                            }
                        }

                        iDia++;

                        if (iDia == 8)
                        {
                            iDia = 1;
                        }
                    }

                    //CALCULA LA MAXIMA CANTIDAD DE SALIDAS DE AVISOS
                    int MaxLines = 0;

                    for (int k = 0; k <= DiasPautados.Length - 1; k++)
                    {
                        if (DiasPautados[k] > MaxLines)
                        {
                            MaxLines = DiasPautados[k];
                        }
                    }

                    oSheet.Cell(22, 2).Value = _Espacio.Name;

                    List<string> IdentifAvisos = new List<string>();

                    for (int i = 0; i <= miDetalle.Count - 1; i++)
                    {

                        if (IdentifAvisos.Count == 0)
                        {
                            IdentifAvisos.Add(miDetalle[i].IdentifAviso);
                        }

                        bool lencontrado = false;

                        string scadena = miDetalle[i].IdentifAviso;

                        for (int j = 0; j <= IdentifAvisos.Count - 1; j++)
                        {
                            if (IdentifAvisos[j] == scadena)
                            {
                                lencontrado = true;

                                break;
                            }
                        }

                        if (!lencontrado)
                        {
                            IdentifAvisos.Add(miDetalle[i].IdentifAviso);

                            break;
                        }
                    }

                    int Fila = 21;

                    for (int i = 0; i <= IdentifAvisos.Count - 1; i++)
                    {
                        aviso = Business.Avisos.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[i]));

                        DTO.PiezasArteDTO pieza = CRUDHelper.Read(string.Format("IdentifPieza = '{0}'", aviso.IdentifPieza),
                                                    BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.PiezasArte));

                        DTO.AnunInternosDTO ai = CRUDHelper.Read(string.Format("IdentifAnun = '{0}'", pieza.IdentifAnun),
                                                        BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AnunInternos));

                        oSheet.Cell(Fila + i, 3).Value = aviso.EtiquetaProd.ToUpper();
                        oSheet.Cell(Fila + i, 4).Value = ai.Name.ToUpper();
                        oSheet.Cell(Fila + i, 6).Value = aviso.Duracion.ToString() + " SEG.";

                        oSheet.Cell(35 + i, 3).Value = aviso.EtiquetaProd.ToUpper();
                        oSheet.Cell(35 + i, 4).Value = ai.Name;
                        oSheet.Cell(35 + i, 5).Value = aviso.Zocalo;
                        oSheet.Cell(35 + i, 6).Value = aviso.NroIngesta;

                        AvisosIdAtenDTO aia = CRUDHelper.Read(string.Format("IdentifAviso = '{0}'", IdentifAvisos[i]), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.AvisosIdAten));

                        oSheet.Cell("D" + (30 + i).ToString()).Value = aia.IdentifIdentAte;

                        int cantsal = 0;

                        decimal CosOp = 0;

                        for (int j = 0; j <= miDetalle.Count - 1; j++)
                        {
                            if (miDetalle[j].IdentifAviso == IdentifAvisos[i])
                            {

                                int ThisDay = (int)miDetalle[j].Dia;
                                int ocurrencias = 0;

                                for (int k = 0; k <= miDetalle.Count - 1; k++)
                                {
                                    if ((int)miDetalle[k].Dia == ThisDay && miDetalle[k].IdentifAviso == IdentifAvisos[i])
                                    {
                                        ocurrencias++;
                                    }
                                }

                                CosOp = miDetalle[j].CostoOp;

                                oSheet.Cell(Fila + i, 6 + ThisDay).Value = ocurrencias;

                                cantsal++;

                            }

                        }

                        oSheet.Cell(Fila + i, 39).Value = CosOp;

                    }

                    oSheet.Name = _Estado.Substring(0, 1).ToUpper() + aniomes + miCabecera.IdentifEspacio;

                    break;
                }
                #endregion
            }


            oWB.SaveAs(nomarchivo);
            oWB.Dispose();
            oSheet = null;
            oWB = null;
            GC.Collect();
        }
Example #26
0
		private void WriteOutZustaendigAGOrtsTeilOrt(ZustaendigAgOrtsTeilOrt ZustaendigAgOrtsTeilOrtInstance,
			StatistikRootClass.StatistikDataSelectionTypes writeOutType, string OutputFileName)
			{
			XLWorkbook workBook = new XLWorkbook();

			IXLWorksheet workSheetOhneOrte = workBook.Worksheets.Add(writeOutType.ToString());
			WriteOutZustaendigAGOrtsTeilOrt(ZustaendigAgOrtsTeilOrtInstance,
				writeOutType, workSheetOhneOrte, false);
			IXLWorksheet workSheetMitOrte = workBook.Worksheets.Add(writeOutType + "_inclOrte");
			WriteOutZustaendigAGOrtsTeilOrt(ZustaendigAgOrtsTeilOrtInstance,
				writeOutType, workSheetMitOrte, true);

			workBook.SaveAs(new FileStream(OutputFileName, FileMode.Create,
				FileAccess.Write, FileShare.ReadWrite));
			workBook.Dispose();
			}
        public void Cabecera_OP_Calendario_Numerico(string nomarchivo)
        {
            ////// ClosedXML ////////
            XLWorkbook oWB = new XLWorkbook(nomarchivo);
            var oSheet = oWB.Worksheet(1);


            string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };

            EmpresaDTO empresa = new DAO.EmpresaDAO().Read(1);

            switch (_Estado.ToUpper())
            {
                case "ORDENADO":
                    {
                        OrdenadoCabDTO miCabecera = (OrdenadoCabDTO)_Cabecera;
                        string aniomes = miCabecera.AnoMes.ToString();
                        oSheet.Cells("C8").Value = miCabecera.PautaId;
                        oSheet.Cells("C11").Value = "'" + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);

                        break;
                    }
                case "ESTIMADO": {

                    EstimadoCabDTO miCabecera = (EstimadoCabDTO)_Cabecera;
                    string aniomes = miCabecera.AnoMes.ToString();
                    oSheet.Cells("C8").Value = miCabecera.PautaId;
                    oSheet.Cells("C11").Value = "'" + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);

                    break;
                }
                case "CERTIFICADO": {

                    CertificadoCabDTO miCabecera = (CertificadoCabDTO)_Cabecera;
                    string aniomes = miCabecera.AnoMes.ToString();
                    oSheet.Cells("C8").Value = miCabecera.PautaId;
                    oSheet.Cells("C11").Value = "'" + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);

                    break; }
            }

            DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));

            oSheet.Cells("C9").Value = medio.Name;
            oSheet.Cells("C10").Value = _Espacio.Name;
            oSheet.Cells("C12").Value = _Espacio.Contacto == null ? "" : _Espacio.Contacto.ToUpper();
            oSheet.Cells("C13").Value = _Espacio.Telefono == null ? "" : "'" + _Espacio.Telefono;
            oSheet.Cells("C14").Value = _Espacio.Direccion == null ? "" : _Espacio.Direccion;
            oSheet.Cells("c15").Value = _Espacio.Email == null ? "" : _Espacio.Email;

            oWB.SaveAs(nomarchivo);
            oWB.Dispose();
            oSheet = null;
            oWB = null;
            GC.Collect(); 
        
        }
Example #28
0
		public void WriteOutNumberOfEntriesPerOrtsTeil(ZustaendigAgOrtsTeilOrt ZustaendigAgOrtsTeilOrtInstance,
			string FileName)
			{
			XLWorkbook workBook = new XLWorkbook();
			foreach (
				StatistikRootClass.DistributionCountTyp distTyp in Enum.GetValues(typeof (StatistikRootClass.DistributionCountTyp)))
				{
				IXLWorksheet workSheet = workBook.Worksheets.Add(distTyp.ToString());
				int StartForContentLine = WriteOutNumberOfEntriesPerOrtsTeil(workSheet, distTyp);
				WriteOutNumberOfEntriesPerOrtsTeil(workSheet, ZustaendigAgOrtsTeilOrtInstance, distTyp,
					StartForContentLine);
				}

			workBook.SaveAs(new FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
			workBook.Dispose();
			}
        public void Cabecera_OP_PNT_Salida(string nomarchivo)
        {
            ////// ClosedXML ////////
            XLWorkbook oWB = new XLWorkbook(nomarchivo);
            var oSheet = oWB.Worksheet(1);

            switch (_Estado.ToUpper())
            {
                case "ORDENADO":
                    {
                        OrdenadoCabDTO miCabecera = (OrdenadoCabDTO)_Cabecera;                        
                        DTO.MediosPubDTO medio = CRUDHelper.Read(string.Format("IdentifMedio = '{0}'", _Espacio.IdentifMedio), BusinessMapper.GetDaoByEntity(BusinessMapper.eEntities.MediosPub));

                        string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
                        string aniomes = miCabecera.AnoMes.ToString();

                        //formato de referencia es [fila, columna]
                        oSheet.Cells("B10").Value = medio.Name;
                        oSheet.Cells("B11").Value = _Espacio.Name;
                        oSheet.Cells("B12").Value = "'" + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);
                        oSheet.Cells("B13").Value = _Espacio.Contacto == null ? "" : _Espacio.Contacto.ToUpper();
                        oSheet.Cells("B14").Value = _Espacio.Telefono == null ? "" : _Espacio.Telefono;
                        oSheet.Cells("B15").Value = _Espacio.Direccion == null ? "" : _Espacio.Direccion.ToUpper();
                        oSheet.Cells("B16").Value = _Espacio.Email == null ? "" : _Espacio.Email;

                        oSheet.Cells("D5").Value = "ORDEN DE PUBLICIDAD - " + _Espacio.Name;

                        //ARMADO DE CALENDARIO - MEJORAR
                        int mes = Convert.ToInt32(aniomes.Substring(4,2));
                        int anio = Convert.ToInt32(aniomes.Substring(0, 4));
                        int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);

                        string[] DiasSemana = { "", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };
                        int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0,4) + "-" + aniomes.Substring(4,2) + "-"  + "01").DayOfWeek);
                        int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);


                        int dia = PrimerDiaMes - PrimerDiaSemana -1;

                        for (int Filas = 20; Filas <= 40; Filas = Filas + 5)
                        {
                            for (int Columnas = 3; Columnas <= 9; Columnas++)
                            {

                                DateTime theDate = new DateTime(anio, 1, 1).AddDays(dia +1);

                                oSheet.Cell(Filas, Columnas).Value = theDate;

                                dia++;
                            }
                        }

                        ////////////////
                        break;
                    }

                case "ESTIMADO": {

                    //formato de referencia es [fila, columna]
                    oSheet.Cells("D5").Value = "ORDEN DE PUBLICIDAD - " + _Espacio.Name;
                    oSheet.Cells("B2").Value = _Espacio.IdentifMedio;
                    oSheet.Cells("B11").Value = _Espacio.Name;

                    string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };

                    EstimadoCabDTO miCabecera = (EstimadoCabDTO)_Cabecera;

                    string aniomes = miCabecera.AnoMes.ToString();

                    oSheet.Cells("B12").Value = "" + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);
                    oSheet.Cells("B13").Value = _Espacio.Contacto == null ? "" : _Espacio.Contacto.ToUpper();
                    oSheet.Cells("B14").Value = _Espacio.Telefono == null ? "" : _Espacio.Telefono;
                    oSheet.Cells("B15").Value = _Espacio.Direccion == null ? "" : _Espacio.Direccion.ToUpper();
                    oSheet.Cells("B16").Value = _Espacio.Email == null ? "" : _Espacio.Email;

                    //ARMADO DE CALENDARIO - MEJORAR
                    int mes = Convert.ToInt32(aniomes.Substring(4, 2));
                    int anio = Convert.ToInt32(aniomes.Substring(0, 4));
                    int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);

                    string[] DiasSemana = { "", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };
                    int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                    int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);


                    int dia = PrimerDiaMes - PrimerDiaSemana + 2;

                    for (int Filas = 20; Filas <= 40; Filas = Filas + 5)
                    {
                        for (int Columnas = 3; Columnas <= 9; Columnas++)
                        {

                            oSheet.Cell(Filas, Columnas).Value = dia;

                            dia++;
                        }
                    }

                    ////////////////
                    break; }

                case "CERTIFICADO": {

                    //formato de referencia es [fila, columna]
                    oSheet.Cells("D5").Value = "ORDEN DE PUBLICIDAD - " + _Espacio.Name;
                    oSheet.Cells("B2").Value = _Espacio.IdentifMedio;
                    oSheet.Cells("B11").Value = _Espacio.Name;

                    string[] Meses = { "", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };

                    CertificadoCabDTO miCabecera = (CertificadoCabDTO)_Cabecera;

                    string aniomes = miCabecera.AnoMes.ToString();

                    oSheet.Cells("B12").Value = "" + Meses[Convert.ToInt32(aniomes.Substring(4, 2))].ToUpper() + "/" + aniomes.Substring(0, 4);
                    oSheet.Cells("B13").Value = _Espacio.Contacto == null ? "" : _Espacio.Contacto.ToUpper();
                    oSheet.Cells("B14").Value = _Espacio.Telefono == null ? "" : _Espacio.Telefono;
                    oSheet.Cells("B15").Value = _Espacio.Direccion == null ? "" : _Espacio.Direccion.ToUpper();
                    oSheet.Cells("B16").Value = _Espacio.Email == null ? "" : _Espacio.Email;

                    //ARMADO DE CALENDARIO - MEJORAR
                    int mes = Convert.ToInt32(aniomes.Substring(4, 2));
                    int anio = Convert.ToInt32(aniomes.Substring(0, 4));
                    int DiasEnMes = System.DateTime.DaysInMonth(anio, mes);

                    string[] DiasSemana = { "", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };
                    int PrimerDiaSemana = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfWeek);
                    int PrimerDiaMes = Convert.ToInt32(Convert.ToDateTime(aniomes.Substring(0, 4) + "-" + aniomes.Substring(4, 2) + "-" + "01").DayOfYear);


                    int dia = PrimerDiaMes - PrimerDiaSemana + 2;

                    for (int Filas = 20; Filas <= 40; Filas = Filas + 5)
                    {
                        for (int Columnas = 3; Columnas <= 9; Columnas++)
                        {

                            oSheet.Cell(Filas, Columnas).Value = dia;

                            dia++;
                        }
                    }

                    ////////////////
                    break;
                }
            }

            oWB.SaveAs(nomarchivo);
            oWB.Dispose();
            oSheet = null;
            oWB = null;
            GC.Collect(); 

        }
        public ActionResult UploadFileForm(HttpPostedFileBase file, int claimId)
        {
            var error = false;
            var message = string.Empty;
            XLWorkbook excBook = null;
            Stream inputStream = null;
            var positions = new List<SpecificationPosition>();
            try
            {
                if (file == null || !file.FileName.EndsWith(".xlsx"))
                {
                    error = true;
                    message = "Файл не предоставлен или имеет неверный формат";
                }
                else
                {
                    var productManagers = UserHelper.GetProductManagers();
                    inputStream = file.InputStream;
                    inputStream.Seek(0, SeekOrigin.Begin);
                    excBook = new XLWorkbook(inputStream);
                    //разбор файла
                    var workSheet = excBook.Worksheet("Лот");
                    if (workSheet != null)
                    {
                        var user = GetUser();
                        //<<<<<<<Номер строки - начало разбора инфы>>>>>>
                        var row = 5;
                        var errorStringBuilder = new StringBuilder();
                        var repeatRowCount = 0;
                        var db = new DbEngine();
                        //var currencies = db.LoadCurrencies();
                        //проход по всем строкам
                        while (true)
                        {
                            var rowValid = true;
                            var model = new SpecificationPosition()
                            {
                                CatalogNumber = string.Empty,
                                Comment = string.Empty,
                                Name = string.Empty,
                                ProductManager = new ProductManager() { Id = string.Empty, Name = string.Empty },
                                Replace = string.Empty,
                                IdClaim = claimId,
                                State = 1,
                                Author = user.Id,
                                Currency = 1,
                            };
                            //получение ячеек с инфой по позициям
                            var numberRange = workSheet.Cell(row, 1);
                            var catalogNumberRange = workSheet.Cell(row, 2);
                            var nameRange = workSheet.Cell(row, 3);
                            //var replaceRange = workSheet.Cell(row, 4);
                            var unitRange = workSheet.Cell(row, 4);
                            var valueRange = workSheet.Cell(row, 5);
                            var managerRange = workSheet.Cell(row, 6);
                            //var currencyRange = workSheet.Cell(row, 8);
                            //var priceRange = workSheet.Cell(row, 9);
                            //var sumRange = workSheet.Cell(row, 10);
                            //var priceTzrRange = workSheet.Cell(row, 11);
                            //var sumTzrRange = workSheet.Cell(row, 12);
                            //var priceNdsRange = workSheet.Cell(row, 13);
                            //var sumNdsRange = workSheet.Cell(row, 14);
                            var commentRange = workSheet.Cell(row, 7);
                            //наименование
                            if (nameRange != null && nameRange.Value != null)
                            {
                                string nameValue = nameRange.Value.ToString();
                                if (string.IsNullOrEmpty(nameValue))
                                {
                                    break;
                                }
                                model.Name = nameValue;
                            }
                            else
                            {
                                break;
                            }
                            //разбор инфы по Порядковый номер
                            if (numberRange != null && numberRange.Value != null)
                            {
                                string numberValue = numberRange.Value.ToString();
                                if (!string.IsNullOrEmpty(numberValue))
                                {
                                    int intValue;
                                    var isValidInt = int.TryParse(numberValue, out intValue);
                                    if (!isValidInt)
                                    {
                                        rowValid = false;
                                        errorStringBuilder.Append("Строка: " + row +
                                                                  ", значение '" + numberValue + "' в поле Порядковый номер не является целым числом<br/>");
                                    }
                                    else
                                    {
                                        model.RowNumber = intValue;
                                    }
                                }
                            }
                            //разбор инфы по Каталожный номер, Замена, Единицы
                            if (catalogNumberRange != null && catalogNumberRange.Value != null)
                            {
                                model.CatalogNumber = catalogNumberRange.Value.ToString();
                            }
                            //if (replaceRange != null && replaceRange.Value != null)
                            //{
                            //    model.Replace = replaceRange.Value.ToString();
                            //}
                            if (unitRange != null && unitRange.Value != null)
                            {
                                var value = unitRange.Value.ToString();
                                switch (value)
                                {
                                    case "шт":
                                        model.Unit = PositionUnit.Thing;
                                        break;
                                    case "упак":
                                        model.Unit = PositionUnit.Package;
                                        break;
                                    case "м":
                                        model.Unit = PositionUnit.Metr;
                                        break;
                                    default:
                                        model.Unit = PositionUnit.Thing;
                                        break;
                                }
                            }
                            else
                            {
                                model.Unit = PositionUnit.Thing;
                            }
                            //разбор инфы по Количество
                            if (valueRange != null)
                            {
                                if (valueRange.Value == null || string.IsNullOrEmpty(valueRange.Value.ToString()))
                                {
                                    rowValid = false;
                                    errorStringBuilder.Append("Строка: " + row +
                                                              ", не задано обязательное значение Количество<br/>");
                                }
                                else
                                {
                                    string valueValue = valueRange.Value.ToString();
                                    int intValue;
                                    var isValidInt = int.TryParse(valueValue, out intValue);
                                    if (!isValidInt)
                                    {
                                        rowValid = false;
                                        errorStringBuilder.Append("Строка: " + row +
                                                                  ", значение '" + valueValue + "' в поле Количество не является целым числом<br/>");
                                    }
                                    else
                                    {
                                        model.Value = intValue;
                                    }
                                }
                            }
                            //разбор инфы по Снабженец
                            if (managerRange == null || managerRange.Value == null || string.IsNullOrEmpty(managerRange.Value.ToString()))
                            {
                                rowValid = false;
                                errorStringBuilder.Append("Строка: " + row +
                                                          ", не задано обязательное значение Снабженец<br/>");
                            }
                            else
                            {
                                var managerFromAd =
                                    productManagers.FirstOrDefault(
                                        x => GetUniqueDisplayName(x) == managerRange.Value.ToString());
                                if (managerFromAd != null) model.ProductManager = managerFromAd;
                                else
                                {
                                    rowValid = false;
                                    errorStringBuilder.Append("Строка: " + row +
                                                              ", не найден Снабженец: " + managerRange.Value + "<br/>");
                                }
                            }
                            if (commentRange != null && commentRange.Value != null)
                            {
                                model.Comment = commentRange.Value.ToString();
                            }
                            //разбор инфы по Ценам и Суммам
                            //if (priceRange != null && priceRange.Value != null)
                            //{
                            //    string priceValue = priceRange.Value.ToString();
                            //    if (!string.IsNullOrEmpty(priceValue))
                            //    {
                            //        double doubleValue;
                            //        var isValidDouble = double.TryParse(priceValue, out doubleValue);
                            //        if (!isValidDouble)
                            //        {
                            //            rowValid = false;
                            //            errorStringBuilder.Append("Строка: " + row +
                            //                                      ", значение '" + priceValue + "' в поле Цена за единицу не является числом<br/>");
                            //        }
                            //        else
                            //        {
                            //            model.Price = doubleValue;
                            //        }
                            //    }
                            //}
                            //if (sumRange != null && sumRange.Value != null)
                            //{
                            //    string sumValue = sumRange.Value.ToString();
                            //    if (!string.IsNullOrEmpty(sumValue))
                            //    {
                            //        double doubleValue;
                            //        var isValidDouble = double.TryParse(sumValue, out doubleValue);
                            //        if (!isValidDouble)
                            //        {
                            //            rowValid = false;
                            //            errorStringBuilder.Append("Строка: " + row +
                            //                                      ", значение '" + sumValue + "' в поле Сумма не является числом<br/>");
                            //        }
                            //        else
                            //        {
                            //            model.Sum = doubleValue;
                            //        }
                            //    }
                            //}
                            //if (priceTzrRange != null && priceTzrRange.Value != null)
                            //{
                            //    string priceTzrValue = priceTzrRange.Value.ToString();
                            //    if (!string.IsNullOrEmpty(priceTzrValue))
                            //    {
                            //        double doubleValue;
                            //        var isValidDouble = double.TryParse(priceTzrValue, out doubleValue);
                            //        if (!isValidDouble)
                            //        {
                            //            rowValid = false;
                            //            errorStringBuilder.Append("Строка: " + row +
                            //                                      ", значение '" + priceTzrValue + "' в поле Цена с ТЗР не является числом<br/>");
                            //        }
                            //        else
                            //        {
                            //            model.PriceTzr = doubleValue;
                            //        }
                            //    }
                            //}
                            //if (sumTzrRange != null && sumTzrRange.Value != null)
                            //{
                            //    string sumTzrValue = sumTzrRange.Value.ToString();
                            //    if (!string.IsNullOrEmpty(sumTzrValue))
                            //    {
                            //        double doubleValue;
                            //        var isValidDouble = double.TryParse(sumTzrValue, out doubleValue);
                            //        if (!isValidDouble)
                            //        {
                            //            rowValid = false;
                            //            errorStringBuilder.Append("Строка: " + row +
                            //                                      ", значение '" + sumTzrValue + "' в поле Сумма с ТЗР не является числом<br/>");
                            //        }
                            //        else
                            //        {
                            //            model.SumTzr = doubleValue;
                            //        }
                            //    }
                            //}
                            //if (priceNdsRange != null && priceNdsRange.Value != null)
                            //{
                            //    string priceNdsValue = priceNdsRange.Value.ToString();
                            //    if (!string.IsNullOrEmpty(priceNdsValue))
                            //    {
                            //        double doubleValue;
                            //        var isValidDouble = double.TryParse(priceNdsValue, out doubleValue);
                            //        if (!isValidDouble)
                            //        {
                            //            rowValid = false;
                            //            errorStringBuilder.Append("Строка: " + row +
                            //                                      ", значение '" + priceNdsValue + "' в поле Цена с НДС не является числом<br/>");
                            //        }
                            //        else
                            //        {
                            //            model.PriceNds = doubleValue;
                            //        }
                            //    }
                            //}
                            //if (sumNdsRange != null && sumNdsRange.Value != null)
                            //{
                            //    string sumNdsValue = sumNdsRange.Value.ToString();
                            //    if (!string.IsNullOrEmpty(sumNdsValue))
                            //    {
                            //        double doubleValue;
                            //        var isValidDouble = double.TryParse(sumNdsValue, out doubleValue);
                            //        if (!isValidDouble)
                            //        {
                            //            rowValid = false;
                            //            errorStringBuilder.Append("Строка: " + row +
                            //                                      ", значение '" + sumNdsValue + "' в поле Сумма с НДС числом<br/>");
                            //        }
                            //        else
                            //        {
                            //            model.SumNds = doubleValue;
                            //        }
                            //    }
                            //}
                            //if (currencyRange != null && currencyRange.Value != null && !string.IsNullOrEmpty(currencyRange.Value.ToString()))
                            //{
                            //    var value = currencyRange.Value.ToString();
                            //    var currency = currencies.FirstOrDefault(x => x.Value == value);
                            //    if (currency != null)
                            //    {
                            //        model.Currency = currency.Id;
                            //    }
                            //    else
                            //    {
                            //        rowValid = false;
                            //        errorStringBuilder.Append("Строка: " + row +
                            //                              ", не найдена Валюта: " + value + "<br/>");
                            //    }
                            //}
                            //else
                            //{
                            //    if (!model.Sum.Equals(0) || !model.Price.Equals(0) || !model.PriceTzr.Equals(0) || !model.SumTzr.Equals(0) || !model.SumNds.Equals(0) || !model.PriceNds.Equals(0))
                            //    {
                            //        rowValid = false;
                            //        errorStringBuilder.Append("Строка: " + row +
                            //                                  ", не задано обязательное значение Валюта<br/>");
                            //    }
                            //    else
                            //    {
                            //        model.Currency = 1;
                            //    }
                            //}
                            if (rowValid)
                            {
                                var isUnique = IsPositionUnique(model, positions);
                                if (isUnique)
                                {
                                    isUnique = db.ExistsSpecificationPosition(model);
                                }
                                if (isUnique)
                                {
                                    positions.Add(model);
                                }
                                else
                                {
                                    repeatRowCount++;
                                }
                            }
                            row++;
                        }
                        //сохранение полученых позиций в БД

                        message = "Получено строк:    " + (row - 5);
                        if (repeatRowCount > 0)
                        {
                            message += "<br/>Из них повторных: " + repeatRowCount;
                        }
                        else
                        {
                            message += "<br/>Из них повторных: 0";
                        }
                        if (positions.Any())
                        {
                            message += "<br/>Сохранено строк:   " + positions.Count();
                        }
                        else
                        {
                            message += "<br/>Сохранено строк:   0";
                        }
                        var errorMessage = errorStringBuilder.ToString();
                        if (!string.IsNullOrEmpty(errorMessage))
                        {
                            message += "<br/>Ошибки:<br/>" + errorMessage;
                        }
                        else
                        {
                            message += "<br/>Ошибки:                   нет";
                        }
                    }
                    else
                    {
                        error = true;
                        message = "Не найден рабочий лист со спецификациями";
                    }
                    excBook.Dispose();
                    excBook = null;
                }
            }
            catch (Exception)
            {
                error = true;
                message = "Ошибка сервера";
            }
            finally
            {
                if (inputStream != null)
                {
                    inputStream.Dispose();
                }
                if (excBook != null)
                {
                    excBook.Dispose();
                }
            }
            ViewBag.FirstLoad = false;
            ViewBag.Error = error.ToString().ToLowerInvariant();
            ViewBag.Message = message;
            ViewBag.Positions = positions;
            ViewBag.IdClaim = claimId;
            return View();
        }
Example #31
0
    public string read_efile()
    {
        string x = "";

        try
        {

            string filename = Server.MapPath("~\\pdf\\" + HttpContext.Current.Session["username"] + "\\Nutratech_DTR.xlsx");

            if (File.Exists(filename))
            {
                ExcelReport.delete_efile();

                XLWorkbook workbook = new XLWorkbook(filename);
                IXLWorksheet ws = workbook.Worksheet(1);

                IXLCell cell = ws.Cell(8, 1);
                string cell_validator = cell.GetString();

                int xrow = 8;
                string xdate = "";
                while (cell_validator != "****** End of File ******")
                {
                    cell = ws.Cell(xrow, 1);

                    IXLCell cell1 = ws.Cell(xrow, 1);
                    IXLCell cell2 = ws.Cell(xrow, 2);
                    IXLCell cell3 = ws.Cell(xrow, 3);
                    IXLCell cell4 = ws.Cell(xrow, 4);
                    IXLCell cell5 = ws.Cell(xrow, 5);
                    IXLCell cell6 = ws.Cell(xrow, 6);
                    IXLCell cell7 = ws.Cell(xrow, 7);
                    IXLCell cell8 = ws.Cell(xrow, 8);
                    IXLCell cell9 = ws.Cell(xrow, 9);

                    string _date_validator = cell1.GetString();
                    try
                    {
                        _date_validator = Convert.ToDateTime(_date_validator).ToShortDateString();
                        xdate = Convert.ToDateTime(_date_validator).ToShortDateString();

                    }
                    catch (Exception ex)
                    {
                    }

                    int _no = -1;
                    string _stremployeeid = "";
                    string _name = "";
                    string _time1 = "";
                    string _time2 = "";
                    string _time3 = "";
                    string _time4 = "";
                    string _log_type = "";
                    string _remarks = "";

                    try
                    {
                        _no = Int32.Parse(cell1.GetString().Replace(".", ""));
                          _stremployeeid = cell2.GetString();
                          _name = cell3.GetString();
                          _time1 = cell4.GetString();
                          _time2 = cell5.GetString();
                          _time3 = cell6.GetString();
                          _time4 = cell7.GetString();
                          _log_type = cell8.GetString().ToUpper().Trim();
                          _remarks = cell9.GetString().Trim();
                    }
                    catch (Exception ex)
                    {
                    }

                    try
                    {

                        if (_time1.Trim() != "")
                        {
                            decimal myDec = Convert.ToDecimal(_time1);

                            DateTime myDate = System.DateTime.FromOADate(Convert.ToDouble(myDec));
                            _time1 = myDate.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        // x = "Error Message : " & ex.Message
                    }
                    try
                    {

                        if (_time2.Trim() != "")
                        {
                            decimal myDec = Convert.ToDecimal(_time2);

                            DateTime myDate = System.DateTime.FromOADate(Convert.ToDouble(myDec));
                            _time2 = myDate.ToString();

                        }
                    }
                    catch (Exception ex)
                    {
                        //  x = "Error Message : " & ex.Message
                    }
                    try
                    {

                        if (_time3.Trim() != "")
                        {
                            decimal myDec = Convert.ToDecimal(_time3);

                            DateTime myDate = System.DateTime.FromOADate(Convert.ToDouble(myDec));
                            _time3 = myDate.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        //    x = "Error Message : " & ex.Message
                    }
                    try
                    {
                        if (_time4.Trim() != "")
                        {
                            decimal myDec = Convert.ToDecimal(_time4);

                            DateTime myDate = System.DateTime.FromOADate(Convert.ToDouble(myDec));
                            _time4 = myDate.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        //   x = "Error Message : " & ex.Message
                    }

                    int _pin = 0;
                    int _employeeid = 0;

                    string _Timedata = "";
                    string _InOut = "";

                    int _Count = 0;
                    bool _Append = true;
                    string _WorkStation = "HRD07";
                    int _Approval = 4;
                    bool _Encode = false;
                    string _Type = "MO";
                    string _DateStamp = System.DateTime.Now.ToString();

                    string _constring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                    if (_no > 0)
                    {
                        string sql = "SELECT EmployeeID, PIN, strEmployeeID FROM Employees WHERE        (strEmployeeID = '" + _stremployeeid + "')";
                        SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringEDS"].ConnectionString);
                        SqlCommand cmd = new SqlCommand(sql, cn);
                        SqlDataReader dtr;

                        cn.Open();
                        dtr = cmd.ExecuteReader();

                        if (dtr.Read())
                        {
                            _employeeid = Convert.ToInt32(dtr["EmployeeID"].ToString().Trim());
                            _pin = Convert.ToInt32(dtr["PIN"].ToString().Trim());

                        }
                        dtr.Close();
                        cn.Close();
                        cn.Dispose();
                        if (_log_type != "" & _remarks != "")
                        {
                            _remarks = _log_type + " - " + _remarks;
                        }
                        else if (_log_type != "" & _remarks == "")
                        {
                            _remarks = _log_type + " - Official Business";
                        }

                        for (int i = 1; i <= 4; i++)
                        {
                            if (i == 1)
                            {
                                if (_time1 != "")
                                {
                                    _Count = i;
                                    _Timedata = Convert.ToDateTime(xdate + " " + Convert.ToDateTime(_time1).ToShortTimeString()).ToString();
                                    _InOut = "IN";
                                    ExcelReport.insert_efile(_Timedata, _employeeid, _pin, _stremployeeid, _Count, _InOut, _remarks, _Append, _WorkStation, _Approval,
                                    _Encode, _Type, _DateStamp, _name, _constring);
                                }
                            }
                            else if (i == 2)
                            {
                                if (_time2 != "")
                                {
                                    _Count = i;
                                    _Timedata = Convert.ToDateTime(xdate + " " + Convert.ToDateTime(_time2).ToShortTimeString()).ToString();
                                    _InOut = "OUT";
                                    ExcelReport.insert_efile(_Timedata, _employeeid, _pin, _stremployeeid, _Count, _InOut, _remarks, _Append, _WorkStation, _Approval,
                                    _Encode, _Type, _DateStamp, _name, _constring);
                                }
                            }
                            else if (i == 3)
                            {
                                if (_time3 != "")
                                {
                                    _Count = i;
                                    _Timedata = Convert.ToDateTime(xdate + " " + Convert.ToDateTime(_time3).ToShortTimeString()).ToString();
                                    _InOut = "IN";
                                    ExcelReport.insert_efile(_Timedata, _employeeid, _pin, _stremployeeid, _Count, _InOut, _remarks, _Append, _WorkStation, _Approval,
                                    _Encode, _Type, _DateStamp, _name, _constring);
                                }
                            }
                            else if (i == 4)
                            {
                                if (_time4 != "")
                                {
                                    _Count = i;
                                    _Timedata = Convert.ToDateTime(xdate + " " + Convert.ToDateTime(_time4).ToShortTimeString()).ToString();
                                    _InOut = "OUT";
                                    ExcelReport.insert_efile(_Timedata, _employeeid, _pin, _stremployeeid, _Count, _InOut, _remarks, _Append, _WorkStation, _Approval,
                                    _Encode, _Type, _DateStamp, _name, _constring);
                                }
                            }
                        }

                        if (_remarks.IndexOf("OB") > -1)
                        {
                            for (int i = (_Count + 1); i <= 4; i++)
                            {
                                if (i == 1)
                                {
                                    if (_time1 == "")
                                    {
                                        _Count = i;
                                        _Timedata = Convert.ToDateTime(xdate + " 8:00:01 AM").ToString();
                                        _InOut = "IN";
                                        ExcelReport.insert_efile(_Timedata, _employeeid, _pin, _stremployeeid, _Count, _InOut, _remarks, _Append, _WorkStation, _Approval,
                                        _Encode, _Type, _DateStamp, _name, _constring);
                                    }
                                    else
                                    {
                                        if (_time1 != "")
                                        {
                                            _Count = i;
                                            _Timedata = Convert.ToDateTime(xdate + " " + Convert.ToDateTime(_time1).ToShortTimeString()).ToString();
                                            _InOut = "IN";
                                            ExcelReport.insert_efile(_Timedata, _employeeid, _pin, _stremployeeid, _Count, _InOut, _remarks, _Append, _WorkStation, _Approval,
                                            _Encode, _Type, _DateStamp, _name, _constring);
                                        }
                                    }
                                }
                                else if (i == 2)
                                {
                                    if (_time2 == "")
                                    {
                                        _Count = i;
                                        _Timedata = Convert.ToDateTime(xdate + " 5:00:01 PM").ToString();
                                        _InOut = "OUT";
                                        ExcelReport.insert_efile(_Timedata, _employeeid, _pin, _stremployeeid, _Count, _InOut, _remarks, _Append, _WorkStation, _Approval,
                                        _Encode, _Type, _DateStamp, _name, _constring);
                                        break; // TODO: might not be correct. Was : Exit For
                                    }
                                    else
                                    {
                                        if (_time2 != "")
                                        {
                                            _Count = i;
                                            _Timedata = Convert.ToDateTime(xdate + " " + Convert.ToDateTime(_time2).ToShortTimeString()).ToString();
                                            _InOut = "OUT";
                                            ExcelReport.insert_efile(_Timedata, _employeeid, _pin, _stremployeeid, _Count, _InOut, _remarks, _Append, _WorkStation, _Approval,
                                            _Encode, _Type, _DateStamp, _name, _constring);
                                        }
                                    }
                                }
                                else if (i == 3)
                                {
                                    if (_time3 == "")
                                    {
                                        _Count = i;
                                        _Timedata = Convert.ToDateTime(xdate + " 1:00:01 PM").ToString();
                                        _InOut = "IN";
                                        ExcelReport.insert_efile(_Timedata, _employeeid, _pin, _stremployeeid, _Count, _InOut, _remarks, _Append, _WorkStation, _Approval,
                                        _Encode, _Type, _DateStamp, _name, _constring);
                                    }
                                    else
                                    {
                                        if (_time3 != "")
                                        {
                                            _Count = i;
                                            _Timedata = Convert.ToDateTime(xdate + " " + Convert.ToDateTime(_time3).ToShortTimeString()).ToString();
                                            _InOut = "IN";
                                            ExcelReport.insert_efile(_Timedata, _employeeid, _pin, _stremployeeid, _Count, _InOut, _remarks, _Append, _WorkStation, _Approval,
                                            _Encode, _Type, _DateStamp, _name, _constring);
                                        }
                                    }
                                }
                                else if (i == 4)
                                {
                                    if (_time4 == "")
                                    {
                                        _Count = i;
                                        _Timedata = Convert.ToDateTime(xdate + " 5:00:01 PM").ToString();
                                        _InOut = "OUT";
                                        ExcelReport.insert_efile(_Timedata, _employeeid, _pin, _stremployeeid, _Count, _InOut, _remarks, _Append, _WorkStation, _Approval,
                                        _Encode, _Type, _DateStamp, _name, _constring);
                                    }
                                    else
                                    {
                                        if (_time4 != "")
                                        {
                                            _Count = i;
                                            _Timedata = Convert.ToDateTime(xdate + " " + Convert.ToDateTime(_time4).ToShortTimeString()).ToString();
                                            _InOut = "OUT";
                                            ExcelReport.insert_efile(_Timedata, _employeeid, _pin, _stremployeeid, _Count, _InOut, _remarks, _Append, _WorkStation, _Approval,
                                            _Encode, _Type, _DateStamp, _name, _constring);
                                        }
                                    }
                                }
                            }
                        }

                    }

                    cell_validator = cell.GetString();
                    xrow += 1;

                }
                ws.Dispose();
                workbook.Dispose();

            }
        }
        catch (Exception ex)
        {
            x = "Error Message : " + ex.Message;
        }

        return x;
    }
 //загрузка списка заявок в excel файл, с учетом фильтра - фильтр передается
 //в параметре modelJson, сериализованный в формат JSON
 public ActionResult GetListExcelFile(string modelJson)
 {
     XLWorkbook excBook = null;
     var ms = new MemoryStream();
     var error = false;
     var message = string.Empty;
     try
     {
         //получение объекта фильтра
         var model = new FilterTenderClaim();
         if (!string.IsNullOrEmpty(modelJson))
         {
             model = JsonConvert.DeserializeObject<FilterTenderClaim>(modelJson);
         }
         if (model.RowCount == 0) model.RowCount = 10;
         //получение отфильтрованной инфы по заявкам из БД
         var db = new DbEngine();
         var list = db.FilterTenderClaims(model);
         var tenderStatus = db.LoadTenderStatus();
         //снабженцв и менеджеры из ActiveDirectory
         var adProductManagers = UserHelper.GetProductManagers();
         var managers = UserHelper.GetManagers();
         if (list.Any())
         {
             db.SetProductManagersForClaims(list);
             var claimProductManagers = list.SelectMany(x => x.ProductManagers).ToList();
             foreach (var claimProductManager in claimProductManagers)
             {
                 var managerFromAD = adProductManagers.FirstOrDefault(x => x.Id == claimProductManager.Id);
                 if (managerFromAD != null)
                 {
                     claimProductManager.Name = managerFromAD.Name;
                     claimProductManager.ShortName = managerFromAD.ShortName;
                 }
             }
             foreach (var claim in list)
             {
                 var manager = managers.FirstOrDefault(x => x.Id == claim.Manager.Id);
                 if (manager != null)
                 {
                     claim.Manager = manager;
                 }
             }
             db.SetStatisticsForClaims(list);
             var dealTypes = db.LoadDealTypes();
             var status = db.LoadClaimStatus();
             //Создание excel файла с инфой о заявках
             excBook = new XLWorkbook();
             var workSheet = excBook.AddWorksheet("Заявки");
             //заголовок
             workSheet.Cell(1, 1).Value = "ID";
             workSheet.Cell(1, 2).Value = "№ Конкурса";
             workSheet.Cell(1, 3).Value = "Контрагент";
             workSheet.Cell(1, 4).Value = "Сумма";
             workSheet.Cell(1, 5).Value = "Менеджер";
             workSheet.Cell(1, 6).Value = "Позиции";
             workSheet.Cell(1, 7).Value = "Снабженцы";
             workSheet.Cell(1, 8).Value = "Тип сделки";
             workSheet.Cell(1, 9).Value = "Статус";
             workSheet.Cell(1, 10).Value = "Создано";
             workSheet.Cell(1, 11).Value = "Срок сдачи";
             workSheet.Cell(1, 12).Value = "Статус конкурса";
             workSheet.Cell(1, 13).Value = "Автор";
             workSheet.Cell(1, 14).Value = "Просроченна";
             var headRange = workSheet.Range(workSheet.Cell(1, 1), workSheet.Cell(1, 14));
             headRange.Style.Font.SetBold(true);
             headRange.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
             headRange.Style.Border.SetBottomBorder(XLBorderStyleValues.Thin);
             headRange.Style.Border.SetBottomBorderColor(XLColor.Gray);
             headRange.Style.Border.SetTopBorder(XLBorderStyleValues.Thin);
             headRange.Style.Border.SetTopBorderColor(XLColor.Gray);
             headRange.Style.Border.SetRightBorder(XLBorderStyleValues.Thin);
             headRange.Style.Border.SetRightBorderColor(XLColor.Gray);
             headRange.Style.Border.SetLeftBorder(XLBorderStyleValues.Thin);
             headRange.Style.Border.SetLeftBorderColor(XLColor.Gray);
             headRange.Style.Fill.BackgroundColor = XLColor.FromArgb(0, 204, 233, 255);
             var row = 2;
             //строки с инфой по заявкам
             foreach (var claim in list)
             {
                 workSheet.Cell(row, 1).Value = claim.Id.ToString("G");
                 workSheet.Cell(row, 2).Value = claim.TenderNumber;
                 workSheet.Cell(row, 3).Value = claim.Customer;
                 workSheet.Cell(row, 4).Value = claim.Sum.ToString("N2");
                 workSheet.Cell(row, 5).Value = claim.Manager.ShortName;
                 workSheet.Cell(row, 6).Value = "Всего: " + claim.PositionsCount + "\rРасчетов: " +
                                                claim.CalculatesCount;
                 workSheet.Cell(row, 7).Value = claim.ProductManagers != null
                     ? string.Join("\r", claim.ProductManagers.Select(x => x.ShortName + " " + x.PositionsCount + "/" + x.CalculatesCount))
                     : string.Empty;
                 workSheet.Cell(row, 8).Value = dealTypes.First(x => x.Id == claim.DealType).Value;
                 workSheet.Cell(row, 9).Value = status.First(x => x.Id == claim.ClaimStatus).Value;
                 workSheet.Cell(row, 10).Value = claim.RecordDate.ToString("dd.MM.yyyy");
                 workSheet.Cell(row, 10).DataType = XLCellValues.DateTime;
                 workSheet.Cell(row, 11).Value = claim.ClaimDeadline.ToString("dd.MM.yyyy");
                 workSheet.Cell(row, 11).DataType = XLCellValues.DateTime;
                 workSheet.Cell(row, 12).Value = tenderStatus.First(x => x.Id == claim.TenderStatus).Value;
                 workSheet.Cell(row, 13).Value = UserHelper.GetUserById(claim.Author.Id).ShortName;
                 var overDie = "Нет";
                 if (claim.ClaimDeadline > DateTime.Now)
                 {
                     if (claim.ClaimStatus != 1 || claim.ClaimStatus != 8)
                     {
                         overDie = "Да";
                     }
                 }
                 workSheet.Cell(row, 14).Value = overDie;
                 row++;
             }
             workSheet.Columns(6, 7).Style.Alignment.WrapText = true;
             workSheet.Columns(1, 14).AdjustToContents();
             excBook.SaveAs(ms);
             excBook.Dispose();
             ms.Seek(0, SeekOrigin.Begin);
         }
         else
         {
             error = true;
             message = "Пустой набор";
         }
     }
     catch (Exception)
     {
         error = true;
         message = "Ошибка сервера";
     }
     finally
     {
         if (excBook != null)
         {
             excBook.Dispose();
         }
     }
     if (!error)
     {
         var date = DateTime.Now.ToString("yyyyMMdd_HHmm");
         return new FileStreamResult(ms, "application/vnd.ms-excel")
         {
             FileDownloadName = "Report-" + date + ".xlsx"
         };
     }
     else
     {
         ViewBag.Message = message;
         return View();
     }
 }
Example #33
0
        // return:
        //      -1  出错
        //      0   放弃或中断
        //      1   成功
        public static int ExportToExcel(
            Stop stop,
            List<ListViewItem> items,
            out string strError)
        {
            strError = "";
            if (items == null || items.Count == 0)
            {
                strError = "items == null || items.Count == 0";
                return -1;
            }
            ListView list = items[0].ListView;

            // 询问文件名
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Title = "请指定要输出的 Excel 文件名";
            dlg.CreatePrompt = false;
            dlg.OverwritePrompt = true;
            // dlg.FileName = this.ExportExcelFilename;
            // dlg.InitialDirectory = Environment.CurrentDirectory;
            dlg.Filter = "Excel 文件 (*.xlsx)|*.xlsx|All files (*.*)|*.*";

            dlg.RestoreDirectory = true;

            if (dlg.ShowDialog() != DialogResult.OK)
                return 0;

            XLWorkbook doc = null;

            try
            {
                doc = new XLWorkbook(XLEventTracking.Disabled);
                File.Delete(dlg.FileName);
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                return -1;
            }

            IXLWorksheet sheet = null;
            sheet = doc.Worksheets.Add("表格");
            // sheet.Style.Font.FontName = this.Font.Name;

            if (stop != null)
                stop.SetProgressRange(0, items.Count);

            // 每个列的最大字符数
            List<int> column_max_chars = new List<int>();

            List<XLAlignmentHorizontalValues> alignments = new List<XLAlignmentHorizontalValues>();
            foreach (ColumnHeader header in list.Columns)
            {
                if (header.TextAlign == HorizontalAlignment.Center)
                    alignments.Add(XLAlignmentHorizontalValues.Center);
                else if (header.TextAlign == HorizontalAlignment.Right)
                    alignments.Add(XLAlignmentHorizontalValues.Right);
                else
                    alignments.Add(XLAlignmentHorizontalValues.Left);

                column_max_chars.Add(0);
            }


            string strFontName = list.Font.FontFamily.Name;

            int nRowIndex = 1;
            int nColIndex = 1;
            foreach (ColumnHeader header in list.Columns)
            {
                IXLCell cell = sheet.Cell(nRowIndex, nColIndex).SetValue(header.Text);
                cell.Style.Alignment.WrapText = true;
                cell.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                cell.Style.Font.Bold = true;
                cell.Style.Font.FontName = strFontName;
                cell.Style.Alignment.Horizontal = alignments[nColIndex - 1];
                nColIndex++;
            }
            nRowIndex++;

            //if (stop != null)
            //    stop.SetMessage("");
            foreach (ListViewItem item in items)
            {
                Application.DoEvents();

                if (stop != null
    && stop.State != 0)
                {
                    strError = "用户中断";
                    return 0;
                }

                // List<CellData> cells = new List<CellData>();

                nColIndex = 1;
                foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
                {
                    // 统计最大字符数
                    int nChars = column_max_chars[nColIndex - 1];
                    if (subitem.Text != null && subitem.Text.Length > nChars)
                    {
                        column_max_chars[nColIndex - 1] = subitem.Text.Length;
                    }
                    IXLCell cell = sheet.Cell(nRowIndex, nColIndex).SetValue(subitem.Text);
                    cell.Style.Alignment.WrapText = true;
                    cell.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                    cell.Style.Font.FontName = strFontName;
                    cell.Style.Alignment.Horizontal = alignments[nColIndex - 1];
                    nColIndex++;
                }

                if (stop != null)
                    stop.SetProgressValue(nRowIndex-1);

                nRowIndex++;
            }

            if (stop != null)
                stop.SetMessage("正在调整列宽度 ...");
            Application.DoEvents();

            double char_width = GetAverageCharPixelWidth(list);

            // 字符数太多的列不要做 width auto adjust
            const int MAX_CHARS = 30;   // 60
            int i = 0;
            foreach (IXLColumn column in sheet.Columns())
            {
                int nChars = column_max_chars[i];
                if (nChars < MAX_CHARS)
                    column.AdjustToContents();
                else
                    column.Width = (double)list.Columns[i].Width / char_width;  // Math.Min(MAX_CHARS, nChars);
                i++;
            }

            // sheet.Columns().AdjustToContents();

            // sheet.Rows().AdjustToContents();

            doc.SaveAs(dlg.FileName);
            doc.Dispose();
            return 1;
        }
        public ActionResult UploadFileForm(HttpPostedFileBase file, int claimId, int cv)
        {
            var error = false;
            var message = string.Empty;
            XLWorkbook excBook = null;
            Stream inputStream = null;
            var positions = new List<SpecificationPosition>();
            try
            {
                if (file == null || !file.FileName.EndsWith(".xlsx"))
                {
                    error = true;
                    message = "Файл не предоставлен или имеет неверный формат";
                }
                else
                {
                    inputStream = file.InputStream;
                    inputStream.Seek(0, SeekOrigin.Begin);
                    excBook = new XLWorkbook(inputStream);
                    var workSheet = excBook.Worksheet("Расчет");
                    //разбор полученного файла
                    if (workSheet != null)
                    {
                        var user = GetUser();
                        //<<<<<<<Номер строки - начало разбора инфы>>>>>>
                        var row = 5;
                        var errorStringBuilder = new StringBuilder();
                        var db = new DbEngine();
                        var emptyRowCount = 0;
                        SpecificationPosition model = null;
                        CalculateSpecificationPosition calculate = null;
                        var protectFacts = db.LoadProtectFacts();
                        var deliveryTimes = db.LoadDeliveryTimes();
                        var currencies = db.LoadCurrencies();
                        var adProductManagers = UserHelper.GetProductManagers();
                        int? idPos = null;
                        //проход по всем строкам
                        while (true)
                        {
                            var rowValid = true;
                            var controlCell = workSheet.Cell(row, 1);

                            //определение типа строки
                            var controlValue = controlCell.Value;
                            bool isCalcRow = false;
                            if (controlValue != null && String.IsNullOrEmpty(controlValue.ToString()) && controlCell.IsMerged() && idPos.HasValue)
                            {
                                controlValue = idPos.Value;
                                isCalcRow = true;
                            }

                            if (controlValue != null || isCalcRow)
                            {
                                if (!isCalcRow)
                                {
                                    var controlValueString = controlValue.ToString();
                                    if (string.IsNullOrEmpty(controlValueString))
                                    {
                                        //Если строка запроса пустая то Конец
                                        if (!workSheet.Cell(row, 3).IsMerged() &&
                                            String.IsNullOrEmpty(workSheet.Cell(row, 3).Value.ToString().Trim()))
                                        {
                                            break;
                                        }

                                        //строка расчета
                                        errorStringBuilder.Append("Не найден идентификатор позиции в строке: " + row + "<br/>");
                                        break;
                                    }
                                    else
                                    {

                                        int id;
                                        var converting = int.TryParse(controlValueString, out id);
                                        if (converting)
                                        {
                                            model = new SpecificationPosition()
                                            {
                                                Calculations = new List<CalculateSpecificationPosition>(),
                                                Author = user.Id
                                            };
                                            model.Id = id;
                                            idPos = id;
                                            positions.Add(model);
                                        }
                                        else
                                        {
                                            errorStringBuilder.Append("Ошибка разбора Id позиции в строке: " + row +
                                                                      "<br/>");
                                            break;
                                        }
                                    }
                                }
                            }

                            //разбор инфы по расчету к позиции

                            //Если строка расчета не пустая, то парсим ее
                            bool flag4Parse = false;
                            for (int i = 4; i <= 15; i++)
                            {
                                if (!String.IsNullOrEmpty(workSheet.Cell(row, i).Value.ToString().Trim()))
                                {
                                    flag4Parse = true;
                                    break;
                                }
                            }

                            if (flag4Parse)
                            {
                                calculate = new CalculateSpecificationPosition()
                                {
                                    IdSpecificationPosition = model.Id,
                                    IdTenderClaim = claimId,
                                    Author = user.Id
                                };

                                //получение значений расчета из ячеек
                                var catalogValue = workSheet.Cell(row, 6).Value;
                                var nameValue = workSheet.Cell(row, 7).Value;
                                var replaceValue = workSheet.Cell(row, 8).Value;
                                var priceUsd = workSheet.Cell(row, 9).Value;
                                var priceEur = workSheet.Cell(row, 10).Value;
                                var priceEurRicoh = workSheet.Cell(row, 11).Value;
                                var priceRubl = workSheet.Cell(row, 12).Value;
                                var providerValue = workSheet.Cell(row, 13).Value;
                                var deliveryTimeValue = workSheet.Cell(row, 14).Value;
                                var protectFactValue = workSheet.Cell(row, 15).Value;
                                var protectConditionValue = workSheet.Cell(row, 16).Value;
                                var commentValue = workSheet.Cell(row, 17).Value;

                                //Проверка
                                if (deliveryTimeValue != null && string.IsNullOrEmpty(deliveryTimeValue.ToString().Trim()))
                                {
                                    rowValid = false;
                                    errorStringBuilder.Append("Строка: " + row +
                                                          ", не задано обязательное значение Срок поставки<br/>");
                                }
                                if ((priceUsd != null && string.IsNullOrEmpty(priceUsd.ToString().Trim()))
                                    && (priceEur != null && string.IsNullOrEmpty(priceEur.ToString().Trim()))
                                    &&
                                    (priceEurRicoh != null && string.IsNullOrEmpty(priceEurRicoh.ToString().Trim()))
                                    && (priceRubl != null && string.IsNullOrEmpty(priceRubl.ToString().Trim())))
                                {
                                    rowValid = false;
                                    errorStringBuilder.Append("Строка: " + row +
                                                          ", не указано ни одной цены<br/>");
                                }

                                //Заполняем
                                calculate.CatalogNumber = catalogValue.ToString();
                                calculate.Name = nameValue.ToString();
                                calculate.Replace = replaceValue.ToString();

                                double prUsd;
                                if (!String.IsNullOrEmpty(priceUsd.ToString().Trim()) && double.TryParse(priceUsd.ToString().Trim(), out prUsd))
                                {
                                    calculate.PriceUsd = prUsd;
                                }

                                double prEur;
                                if (!String.IsNullOrEmpty(priceEur.ToString().Trim()) && double.TryParse(priceEur.ToString().Trim(), out prEur))
                                {
                                    calculate.PriceEur = prEur;
                                }

                                double prEurRicoh;
                                if (!String.IsNullOrEmpty(priceEurRicoh.ToString().Trim()) && double.TryParse(priceEurRicoh.ToString().Trim(), out prEurRicoh))
                                {
                                    calculate.PriceEurRicoh = prEurRicoh;
                                }

                                double prRubl;
                                if (!String.IsNullOrEmpty(priceRubl.ToString().Trim()) && double.TryParse(priceRubl.ToString().Trim(), out prRubl))
                                {
                                    calculate.PriceRubl = prRubl;
                                }

                                calculate.Provider = providerValue.ToString();

                                var delivertTimeValueString = deliveryTimeValue.ToString().Trim();
                                var possibleDelTimValues = deliveryTimes.Select(x => x.Value);
                                if (!possibleDelTimValues.Contains(delivertTimeValueString))
                                {
                                    rowValid = false;
                                    errorStringBuilder.Append("Строка: " + row +
                                                          ", Значение '" + delivertTimeValueString + "' не является допустимым для Срок поставки<br/>");
                                }
                                else
                                {
                                    var delTime = deliveryTimes.First(x => x.Value == delivertTimeValueString);
                                    calculate.DeliveryTime = delTime;
                                }

                                var protectFactValueString = protectFactValue.ToString().Trim();
                                var possibleValues = protectFacts.Select(x => x.Value);
                                if (!possibleValues.Contains(protectFactValueString))
                                {
                                    //rowValid = false;
                                    //errorStringBuilder.Append("Строка: " + row +
                                    //                      ", Значение '" + protectFactValueString + "' не является допустимым для Факт получ.защиты<br/>");
                                    calculate.ProtectFact = null;
                                }
                                else
                                {
                                    var fact = protectFacts.First(x => x.Value == protectFactValueString);
                                    calculate.ProtectFact = fact;
                                }

                                calculate.ProtectCondition = protectConditionValue.ToString();
                                calculate.Comment = commentValue.ToString();

                                //Если есть ошибки то не добавляем
                                if (rowValid)model.Calculations.Add(calculate);
                            }

                            row++;
                        }

                        //получение позиций для текущего юзера
                        var userPositions = new List<SpecificationPosition>();
                        if (UserHelper.IsController(user))
                        {
                            userPositions = db.LoadSpecificationPositionsForTenderClaim(claimId, cv);
                        }
                        else if (UserHelper.IsProductManager(user))
                        {
                            userPositions = db.LoadSpecificationPositionsForTenderClaimForProduct(claimId, user.Id, cv);
                        }
                        //позиции доступные для изменения
                        var possibleEditPosition = userPositions.Where(x => x.State == 1 || x.State == 3).ToList();
                        if (possibleEditPosition.Any())
                        {
                            //сохранение позиций и расчета к ним в БД
                            db.DeleteCalculateForPositions(claimId, possibleEditPosition);
                            var userPositionsId = possibleEditPosition.Select(x => x.Id).ToList();
                            var positionCalculate = 0;
                            var calculateCount = 0;
                            if (positions != null && positions.Any())
                            {
                                foreach (var position in positions)
                                {
                                    if (!userPositionsId.Contains(position.Id)) continue;
                                    if (position.Calculations.Any()) positionCalculate++;
                                    foreach (var calculatePosition in position.Calculations)
                                    {
                                        calculateCount++;
                                        calculatePosition.IdSpecificationPosition = position.Id;
                                        calculatePosition.IdTenderClaim = claimId;
                                        db.SaveCalculateSpecificationPosition(calculatePosition);
                                    }
                                }
                            }
                            var errorPart = errorStringBuilder.ToString().Trim();
                            if (string.IsNullOrEmpty(errorPart)) errorPart = "нет";
                            else errorPart = "<br/>" + errorPart;
                            message = "Позиций расчитано: " + positionCalculate + "<br/>Строк расчета: " +
                                      calculateCount + "<br/>Ошибки: " + errorPart;
                        }
                        else
                        {
                            var errorPart = errorStringBuilder.ToString().Trim();
                            if (string.IsNullOrEmpty(errorPart)) errorPart = "нет";
                            else errorPart = "<br/>" + errorPart;
                            message = "нет позиций для расчета<br/>Ошибки: " + errorPart;
                        }
                        //получение позиций и расчетов к ним для текущего юзера для передачи в ответ
                        var isController = UserHelper.IsController(user);
                        if (!isController)
                        {
                            positions = db.LoadSpecificationPositionsForTenderClaimForProduct(claimId,
                                user.Id, cv);
                        }
                        else
                        {
                            positions = db.LoadSpecificationPositionsForTenderClaim(claimId, cv);
                        }
                        var productManagers = positions.Select(x => x.ProductManager).ToList();
                        foreach (var productManager in productManagers)
                        {
                            var productManagerFromAd = adProductManagers.FirstOrDefault(x => x.Id == productManager.Id);
                            if (productManagerFromAd != null)
                            {
                                productManager.Name = productManagerFromAd.Name;
                            }
                        }
                        var calculations = db.LoadCalculateSpecificationPositionsForTenderClaim(claimId, cv);
                        if (calculations != null && calculations.Any())
                        {
                            foreach (var position in positions)
                            {
                                position.Calculations =
                                    calculations.Where(x => x.IdSpecificationPosition == position.Id).ToList();
                            }
                        }
                    }
                    else
                    {
                        error = true;
                        message = "Не найден рабочий лист с расчетом спецификаций";
                    }
                    excBook.Dispose();
                    excBook = null;
                }
            }
            catch (Exception)
            {
                error = true;
                message = "Ошибка сервера";
            }
            finally
            {
                if (inputStream != null)
                {
                    inputStream.Dispose();
                }
                if (excBook != null)
                {
                    excBook.Dispose();
                }
            }
            ViewBag.FirstLoad = false;
            ViewBag.Error = error.ToString().ToLowerInvariant();
            ViewBag.Message = message;
            ViewBag.Positions = positions;
            ViewBag.ClaimId = claimId;
            return View();
        }