예제 #1
0
        public byte[] ExecuteTableReport(TableReportContext context)
        {
            try
            {
                using (var stream = new MemoryStream())
                {
                    // DONE: Реализовать генерацию отчета
                    var xlsDefBuilder = Provider.Get <IBuilder <ReportDef, XlsDef> >();
                    using (var xlsDef = xlsDefBuilder.Build(context.Def))
                    {
                        var builder = new XlsBuilder(xlsDef);
                        using (var workbook = builder.Build())
                        {
                            workbook.Write(stream);

                            return(stream.ToArray());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                try
                {
                    var fn = Logger.GetLogFileName("ReportManagerError");
                    Logger.OutputLog(fn, e, "ExecuteTableReport Error");
                }
                catch
                {
                }
                throw;
            }
        }
예제 #2
0
        public void TestMethod11()
        {
            using (var def = new XlsDef())
            {
                // Header
                def.AddArea().AddRow() /*.AddEmptyCell()*/;
                def.AddArea().AddRow().AddText("Еженедельные сведения по компенсационным выплатам", 9);
                def.AddArea().AddRow().AddEmptyCell();

                // Grid Header
                var h1 = def.AddArea().AddRow();
                h1.AddNode("виды компенсаций", 0, 2);
                h1.AddNode("Численность", 0, 2);
                h1.AddNode("Задолженность", 0, 2);
                var node1 = h1.AddNode("С начала года", 2);
                node1.AddNode("Потребная сумма");
                node1.AddNode("Профинансированно");

                var node2 = h1.AddNode("в текущем месяце", 2);
                node2.AddNode("Потребная сумма");
                node2.AddNode("Профинансированно");

                var node3 = h1.AddNode("Задолженность", 2);
                node3.AddNode("от потребной суммы");
                node3.AddNode("от месячной профинансированной суммы");

                var builder  = new XlsBuilder(def);
                var workbook = builder.Build();
                using (var stream = new FileStream(@"c:\distr\cissa\testXlsDef2.xls", FileMode.Create))
                {
                    workbook.Write(stream);
                }
            }
        }
예제 #3
0
        /// <summary>
        /// Формирует Excel документ из формы и запроса выборки данных
        /// </summary>
        /// <param name="form">Форма, задающая оформление данных в выходном документе</param>
        /// <param name="queryDef">Запрос для выборки данных из БД</param>
        /// <returns>Массив двоичных данных тела Excel файла</returns>
        public byte[] ExcelFromQuery(BizForm form, QueryDef queryDef)
        {
            var sqb = _sqlQueryBuilderFactory.Create();

            using (var sqlQuery = sqb.Build(queryDef, form, null, null))
            {
                sqlQuery.AddAttribute("&Id");

                using (var sqlReader = _sqlQueryReaderFactory.Create(sqlQuery) /*new SqlQueryReader(DataContext, sqlQuery)*/)
                {
                    var defBuilder = new XlsGridDefBuilder(Provider, form, sqlReader);

                    using (var def = defBuilder.BuildFromBizForm())
                    {
                        var builder = new XlsBuilder(def);
                        using (var workbook = builder.Build())
                        {
                            using (var stream = new MemoryStream())
                            {
                                workbook.Write(stream);

                                return(stream.ToArray());
                            }
                        }
                    }
                }
            }
        }
예제 #4
0
        /// <summary>
        /// Формирует Excel документ из формы и критериев выборки
        /// </summary>
        /// <param name="form">Форма, задающая оформление данных в выходном документе</param>
        /// <param name="docStateId">Идентификатор статуса документа в качестве критерия выборки документов из БД</param>
        /// <param name="filter">Форма фильтра с данными для ограничения выборки документов</param>
        /// <returns>Массив двоичных данных тела Excel файла</returns>
        public byte[] ExcelFromFormFilter(BizForm form, Guid?docStateId, BizForm filter)
        {
            var sqb = _sqlQueryBuilderFactory.Create();

            using (var query = sqb.Build(form, docStateId, filter, null))
            {
                using (var reader = _sqlQueryReaderFactory.Create(query))
                {
                    var defBuilder = new XlsGridDefBuilder(Provider, form, reader);
                    using (var def = defBuilder.BuildFromBizForm())
                    {
                        var builder = new XlsBuilder(def);
                        using (var workbook = builder.Build())
                        {
                            using (var stream = new MemoryStream())
                            {
                                workbook.Write(stream);

                                return(stream.ToArray());
                            }
                        }
                    }
                }
            }
        }
예제 #5
0
        public void XlsGridReportDefBuilderTest()
        {
            using (var connection = new SqlConnection(CissaConnectionString))
            {
                using (var dataContext = new DataContext(connection))
                {
                    using (var provider = AppProvider.CreateProvider(dataContext))
                    {
                        var formRepo = provider.Get <IFormRepository>(); //new FormRepository(dataContext);
                        var form     = formRepo.GetTableForm(Guid.Parse("{B46A77AB-3F36-42CD-998A-018BE911AD16}"));

                        var defRepo = provider.Get <IDocDefRepository>(); //new DocDefRepository(dataContext);
                        var docDef  = defRepo.DocDefById(form.DocumentDefId ?? Guid.Empty);

                        var qb = new QueryBuilder(docDef.Id);
                        qb.Where("PostCode").Eq("10");
                        var sqlQueryBuilder = provider.Get <ISqlQueryBuilder>();
                        //var query = new DocQuery(qb.Def, dataContext);
                        var query = sqlQueryBuilder.Build(qb.Def, form, null /*, Guid.Empty, dataContext*/);
                        query.TopNo = 100;
                        using (var reader = new SqlQueryReader(dataContext, query))
                        {
                            var defBuilder = new XlsGridReportDefBuilder(dataContext, form, reader /*.All()*/,
                                                                         Guid.Empty);
                            defBuilder.AddHeaderText("Тестовый отчет").Bold().Center().FontDSize(4);
                            defBuilder.AddHeaderText("за 04.2015").Bold().Center();

                            defBuilder.AddFooterText("Подпись: ").Right().Margins(10, 10);
                            var table = defBuilder.AddFooterTable();
                            table.Bold().Center().Margins(30, 30).Style.Borders = TableCellBorder.All;
                            table.Add(0, 0, "Руководитель");
                            table.Add(1, 0, "Финансовый менеджер");
                            table.Add(2, 0, "Начальник отдела АСП");
                            table.Add(0, 1, "Подпись");
                            table.Add(1, 1, "Подпись");
                            table.Add(2, 1, "Подпись");
                            table.Add(0, 2, "Дата");
                            table.Add(1, 2, "Дата");
                            table.Add(2, 2, "Дата").Italic().Right();

                            var def = defBuilder.BuildFromBizForm();
                            def.Style.FontName = "Arial Narrow";
                            def.Style.VAlign   = VAlignment.Middle;

                            var builder  = new XlsBuilder(def);
                            var workbook = builder.Build();

                            using (
                                var stream = new FileStream(@"c:\distr\cissa\testXlsGridReportDefBuilder.xls",
                                                            FileMode.Create))
                            {
                                workbook.Write(stream);
                            }
                        }
                    }
                }
            }
        }
예제 #6
0
        /// <summary>
        /// Формирует Excel документ из формы и списка документов
        /// </summary>
        /// <param name="form">Форма, задающая оформление данных в выходном документе</param>
        /// <param name="docIdList">Список идентификаторов документов, которые необходимо вывести в файл</param>
        /// <returns>Массив двоичных данных тела Excel файла</returns>
        public byte[] ExcelFromDocIdList(BizForm form, List <Guid> docIdList)
        {
            var defBuilder = new XlsGridDefBuilder(DataContext, form, docIdList, CurrentUserId);

            using (var def = defBuilder.BuildFromBizForm())
            {
                var builder = new XlsBuilder(def);
                using (var workbook = builder.Build())
                {
                    using (var stream = new MemoryStream())
                    {
                        workbook.Write(stream);

                        return(stream.ToArray());
                    }
                }
            }
        }
예제 #7
0
        public void TestMethod3()
        {
            using (var connection = new SqlConnection(CissaConnectionString))
            {
                using (var dataContext = new DataContext(connection))
                {
                    using (var provider = AppProvider.CreateProvider(dataContext))
                    {
                        var formRepo = provider.Get <IFormRepository>(); //new FormRepository(dataContext);
                        var form     = formRepo.GetTableForm(Guid.Parse("{B46A77AB-3F36-42CD-998A-018BE911AD16}"));

                        var defRepo = provider.Get <IDocDefRepository>(); // new DocDefRepository(dataContext);
                        var docDef  = defRepo.DocDefById(form.DocumentDefId ?? Guid.Empty);

                        var qb = new QueryBuilder(docDef.Id);
                        qb.Where("PostCode").Eq("10");
                        var sqlQueryBuilder = provider.Get <ISqlQueryBuilder>();
                        //var query = new DocQuery(qb.Def, dataContext);
                        using (var query = sqlQueryBuilder.Build(qb.Def, form, null))
                        {
                            query.TopNo = 100;
                            using (var reader = new SqlQueryReader(dataContext, query))
                            {
                                var defBuilder = new XlsGridDefBuilder(provider, form, reader /*.All()*/);
                                var def        = defBuilder.BuildFromBizForm();
                                def.Style.FontName = "Arial Narrow";
                                def.Style.VAlign   = VAlignment.Middle;

                                var builder  = new XlsBuilder(def);
                                var workbook = builder.Build();

                                using (
                                    var stream = new FileStream(@"c:\distr\cissa\testXlsDefApps.xls", FileMode.Create))
                                {
                                    workbook.Write(stream);
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #8
0
        public void XlsFormDefBuilderTest()
        {
            using (var dataContext = new DataContext())
            {
                var formRepo = new FormRepository(dataContext);
                var form     = formRepo.GetDetailForm(Guid.Parse("{90958557-E6B0-40A8-88D8-75B71130D5FC}"));

                var docRepo = new DocRepository(dataContext);
                var doc     = docRepo.LoadById(Guid.Parse("626b662c-17a9-4f70-9a06-13d2337a681a"));

                var defBuilder = new XlsFormDefBuilder(dataContext, form, Guid.Empty);
                var def        = defBuilder.Build(doc);
                def.Style.Borders = TableCellBorder.All;

                var builder  = new XlsBuilder(def);
                var workbook = builder.Build();
                using (var stream = new FileStream(@"c:\distr\cissa\testXlsDefAppForm.xls", FileMode.Create))
                {
                    workbook.Write(stream);
                }
            }
        }
예제 #9
0
        public byte[] ExcelFromDetailForm(BizForm form, Doc doc)
        {
            var factory = Provider.Get <IXlsFormDefBuilderFactory>();

            var defBuilder = factory.Create(form);

            using (var def = defBuilder.Build(doc))
            {
                def.Style.Borders = TableCellBorder.All;

                var builder = new XlsBuilder(def);
                using (var workbook = builder.Build())
                {
                    using (var stream = new MemoryStream())
                    {
                        workbook.Write(stream);

                        return(stream.ToArray());
                    }
                }
            }
        }
예제 #10
0
        public void TestMethod2()
        {
            using (var connection = new SqlConnection(ChatkalConnectionString))
            {
                using (var dataContext = new DataContext(connection))
                {
                    using (var mdc = new MultiDataContext(new[] { dataContext }))
                    {
                        var factory = AppServiceProviderFactoryProvider.GetFactory();
                        using (var provider = factory.Create())
                        {
                            var defRepo = provider.Get <IDocDefRepository>(); // new DocDefRepository(dataContext);
                            var docDef  = defRepo.DocDefByName("Person-Sheet");

                            using (var def = new XlsDef())
                            {
                                // Header
                                def.Style.FontName = "Arial Narrow";
                                def.AddArea().AddRow().AddEmptyCell();
                                def.AddArea().AddRow().AddText("Список граждан");
                                def.AddArea().AddRow().AddEmptyCell();

                                // Grid Header
                                var h1 = def.AddArea().AddRow();
                                foreach (var attr in docDef.Attributes)
                                {
                                    h1.AddNode(attr.Name).ShowAllBorders(true);
                                }

                                var qb = new QueryBuilder(docDef.Id);
                                qb.Where("LastName").Contains("ИВАН");

                                var sqlQueryBuilder = provider.Get <ISqlQueryBuilder>();
                                var query           = sqlQueryBuilder.Build(qb.Def);
                                query.AddAttribute("&Id");
                                var list = new List <Guid>();
                                using (var r = new SqlQueryReader(dataContext, query))
                                    while (r.Read())
                                    {
                                        list.Add(r.GetGuid(0));
                                    }
                                using (var docDataSet = new DocDataSet(provider, dataContext, list, Guid.Empty))
                                {
                                    var gridRow = def.AddGrid(docDataSet).AddRow();
                                    foreach (var attr in docDef.Attributes)
                                    {
                                        gridRow.ShowAllBorders(true);
                                        gridRow.Style.AutoWidth  = true;
                                        gridRow.Style.AutoHeight = true;
                                        gridRow.AddDataField(new DocDataSetField(docDataSet, attr));
                                    }

                                    var builder  = new XlsBuilder(def);
                                    var workbook = builder.Build();
                                    using (
                                        var stream = new FileStream(@"c:\distr\cissa\testXlsDefPersons.xls", FileMode.Create))
                                    {
                                        workbook.Write(stream);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #11
0
        public byte[] ExcelFromDocumentListForm(Guid documentId, BizDocumentListForm docListForm)
        {
            var form = docListForm.TableForm;

            if (form == null && docListForm.FormId != null)
            {
                form = FormRepo.GetTableForm((Guid)docListForm.FormId);
            }
            if (form == null)
            {
                throw new ApplicationException("Табличная форма не указана!");
            }

            var sqb = _sqlQueryBuilderFactory.Create();

            if (docListForm.AttributeDefId != null)
            {
                using (var query = sqb.BuildAttrList(form, documentId, (Guid)docListForm.AttributeDefId, null, null))
                {
                    query.WithNoLock = true;

                    using (var reader = _sqlQueryReaderFactory.Create(query))
                    {
                        var defBuilder = new XlsGridDefBuilder(Provider, form, reader);
                        using (var def = defBuilder.BuildFromBizForm())
                        {
                            var builder = new XlsBuilder(def);
                            using (var workbook = builder.Build())
                            {
                                using (var stream = new MemoryStream())
                                {
                                    workbook.Write(stream);

                                    return(stream.ToArray());
                                }
                            }
                        }
                    }
                }
            }

            if (docListForm.FormAttributeDefId != null)
            {
                using (var query = sqb.BuildRefList(form, documentId, (Guid)docListForm.FormAttributeDefId, null, null))
                {
                    using (var reader = _sqlQueryReaderFactory.Create(query)) //new SqlQueryReader(DataContext, query))
                    {
                        var defBuilder = new XlsGridDefBuilder(Provider, form, reader);
                        using (var def = defBuilder.BuildFromBizForm())
                        {
                            var builder = new XlsBuilder(def);
                            using (var workbook = builder.Build())
                            {
                                using (var stream = new MemoryStream())
                                {
                                    workbook.Write(stream);

                                    return(stream.ToArray());
                                }
                            }
                        }
                    }
                }
            }

            throw new ApplicationException("Не могу сформировать Excel файл! Атрибут не указан!");
        }
예제 #12
0
        public void XlsTestMethod()
        {
            using (var connection = new SqlConnection(AsistConnectionString))
            {
                using (var dataContext = new DataContext(connection))
                {
                    using (var provider = GetProvider(dataContext))
                    {
                        using (var def = new XlsDef())
                        {
                            var qb = new QueryBuilder(PaymentDefId);
                            //qb.Where("Registry").Eq(sheet.Id);
                            var sqlQueryBuilder = provider.Get <ISqlQueryBuilder>();
                            var query           = sqlQueryBuilder.Build(qb.Def);
                            var bankAccountSrc  = query.JoinSource(query.Source, BankAccountDefId,
                                                                   SqlSourceJoinType.Inner,
                                                                   "BankAccount");
                            var assignSrc = query.JoinSource(query.Source, AssignmentDefId, SqlSourceJoinType.Inner,
                                                             "Assignment");
                            var appSrc      = query.JoinSource(assignSrc, AppDefId, SqlSourceJoinType.Inner, "Application");
                            var personSrc   = query.JoinSource(appSrc, PersonDefId, SqlSourceJoinType.Inner, "Person");
                            var appStateSrc = query.JoinSource(appSrc, AppStateDefId, SqlSourceJoinType.Inner,
                                                               "Application_State");
                            var districtSrc = query.JoinSource(appStateSrc, DistrictDefId, SqlSourceJoinType.LeftOuter,
                                                               "DistrictId");
                            query.AddAttribute(personSrc, "IIN");
                            query.AddAttribute(bankAccountSrc, "Account_No");
                            query.AddAttribute(personSrc, "Last_Name");
                            query.AddAttribute(personSrc, "First_Name");
                            query.AddAttribute(personSrc, "Middle_Name");
                            query.AddAttribute(personSrc, "PassportSeries");
                            query.AddAttribute(personSrc, "PassportNo");
                            query.AddAttribute("&Id");
                            query.AddAttribute(assignSrc, "Amount");


                            var h = def.AddArea().AddRow();
                            h.AddNode("Id");
                            h.AddNode("ПИН");
                            h.AddNode("Номер банковского счета");
                            h.AddNode("Фамилия, Имя, Отчество");
                            h.AddNode("Номер паспорта");
                            h.AddNode("Сумма пособия");

                            using (var reader = new SqlQueryReader(dataContext, query))
                            {
                                while (reader.Read())
                                {
                                    var     inn       = !reader.IsDbNull(0) ? reader.GetString(0) : "";
                                    var     accountNo = !reader.IsDbNull(1) ? reader.GetString(1) : "";
                                    var     ln        = !reader.IsDbNull(2) ? reader.GetString(2) : "";
                                    var     fn        = !reader.IsDbNull(3) ? reader.GetString(3) : "";
                                    var     mn        = !reader.IsDbNull(4) ? reader.GetString(4) : "";
                                    var     ps        = !reader.IsDbNull(5) ? reader.GetString(5) : "";
                                    var     pNo       = !reader.IsDbNull(6) ? reader.GetString(6) : "";
                                    var     id        = !reader.IsDbNull(7) ? reader.GetGuid(7) : Guid.Empty;
                                    decimal amount    = !reader.IsDbNull(8) ? reader.GetDecimal(8) : 0;

                                    var r = def.AddArea().AddRow();
                                    r.AddColumn().AddText(id.ToString());
                                    r.AddColumn().AddText(inn);
                                    r.AddColumn().AddText(accountNo);
                                    r.AddColumn().AddText(string.Format("{0} {1} {2}", ln, fn, mn));
                                    r.AddColumn().AddText(string.Format("{0} {1}", ps, pNo));
                                    r.AddColumn().AddFloat((double)amount);
                                }
                            }

                            var builder  = new XlsBuilder(def);
                            var workbook = builder.Build();
                            using (
                                var stream = new FileStream(
                                    "c:\\distr\\cissa\\UnloadingBankPaymentRegistry.xls", FileMode.Create))
                            {
                                workbook.Write(stream);
                            }
                        }
                    }
                }
            }
        }
예제 #13
0
        public FileResult GetFile(int reportId)
        {
            var report = db.Reports.Find(reportId);
            var HumDistributionPlan = db.HumDistributionPlans.Find(report.HumDistributionPlanId ?? 0);

            string filepath = "C://CissaFiles//Report.xls";//Server.MapPath("~/Doc/ExcelPlan.xls");

            using (var def = new XlsDef())
            {
                def.AddArea().AddRow().AddEmptyCell();
                var s5 = def.AddArea().AddRow();
                s5.AddText("Отчет получателя \"" + HumDistributionPlan.Company.Name + "\" о предоставлении гуманитарной помощи", 10);
                s5.Style.HAlign = HAlignment.Center; //По центру
                s5.Style.Bold();
                def.AddArea().AddEmptyRow();
                var h = def.AddArea().AddRow();
                h.AddText("№");
                h.AddText("Потребитель / Организация");
                h.AddText("Регион");
                h.AddText("Адрес");
                h.AddText("Наименование гум. помощи (товара)");
                h.AddText("Ед. изм.");
                h.AddText("Кол-во (план)");
                //h.AddText("Вес (кг) (план)");
                h.AddText("Сумма (сом)(план)*");
                h.AddText("Кол-во (факт)");
                //h.AddText("Вес (кг) (факт)");
                h.AddText("Сумма (факт)*");
                h.AddText("Кол-во (остаток)");
                //h.AddText("Вес (кг) (остаток)");
                h.AddText("Сумма (остаток)*");
                h.ShowAllBorders(true);
                h.Style.FontStyle  = FontStyle.Bold;                //Шрифт жирный
                h.Style.HAlign     = HAlignment.Center;             //По центру
                h.Style.BgColor    = IndexedColors.BLUE_GREY.Index; //48; Цвет шапки
                h.Style.FontColor  = IndexedColors.WHITE.Index;     //Цвет шрифта
                h.Style.WrapText   = true;
                h.Style.AutoWidth  = true;
                h.Style.AutoHeight = true;
                int     i             = 1;
                double  planAmount    = 0;
                decimal planSum       = 0;
                double  factAmount    = 0;
                decimal factSum       = 0;
                double  balanceAmount = 0;
                decimal balanceSum    = 0;
                foreach (var item in db.ReportItems.Where(x => x.ReportId == reportId).Include(x => x.HumDistributionPlanItem).ToList())
                {
                    var r = def.AddArea().AddRow();
                    r.AddColumn().AddInt(i);
                    r.AddColumn().AddText(item.HumDistributionPlanItem.Consumer.Name);
                    r.AddColumn().AddText(item.HumDistributionPlanItem.Area.Name);
                    r.AddColumn().AddText(item.HumDistributionPlanItem.Address);
                    r.AddColumn().AddText(item.HumDistributionPlanItem.Product.Name);
                    r.AddColumn().AddText(item.HumDistributionPlanItem.UnitType.Name);
                    r.AddColumn().AddFloat(item.HumDistributionPlanItem.Amount ?? 0);
                    //r.AddColumn().AddText("");
                    r.AddColumn().AddFloat((double)(item.HumDistributionPlanItem.Sum ?? 0));
                    r.AddColumn().AddFloat(item.FactAmount ?? 0);
                    //r.AddColumn().AddText("");
                    r.AddColumn().AddFloat((double)(item.FactSum ?? 0));
                    r.AddColumn().AddFloat(item.BalanceAmount ?? 0);
                    //r.AddColumn().AddText("");
                    r.AddColumn().AddFloat((double)(item.BalanceSum ?? 0));
                    r.ShowAllBorders(true);
                    i++;

                    planAmount    += item.HumDistributionPlanItem.Amount ?? 0;
                    planSum       += item.HumDistributionPlanItem.Sum ?? 0;
                    factAmount    += item.FactAmount ?? 0;
                    factSum       += item.FactSum ?? 0;
                    balanceAmount += item.BalanceAmount ?? 0;
                    balanceSum    += item.BalanceSum ?? 0;
                }
                var f = def.AddArea().AddRow();
                f.AddText("Итого:", 6);
                f.AddFloat(planAmount);
                f.AddFloat((double)planSum);
                f.AddFloat(factAmount);
                f.AddFloat((double)factSum);
                f.AddFloat(balanceAmount);
                f.AddFloat((double)balanceSum);
                f.ShowAllBorders(true);
                f.Style.HAlign = HAlignment.Right;
                f.Style.Bold();

                def.AddArea().AddRow().AddEmptyCell();
                var s1 = def.AddArea().AddRow();
                s1.AddText("ФИО руководителя организации", 3);
                var s3 = def.AddArea().AddRow();
                s3.AddText("______________________", 3);
                s3.AddText("подпись");
                def.AddArea().AddEmptyRow();
                var s4 = def.AddArea().AddRow();
                s4.AddText("Дата: ", 3);
                s4.AddText("«    » _____________ 20___");
                def.AddArea().AddEmptyRow();
                var s4_1 = def.AddArea().AddRow();
                s4_1.AddText("М.П.", 3);
                def.AddArea().AddEmptyRow();
                var s4_2 = def.AddArea().AddRow();
                s4_2.AddText("* сумма указана донором только для таможенных целей", 3);
                var builder  = new XlsBuilder(def);
                var workbook = builder.Build();


                using (var stream = new FileStream(filepath, FileMode.Create))
                {
                    workbook.Write(stream);
                }
                return(File(filepath, "application/vnd.ms-excel", "Report.xls"));
            }
        }
        public FileResult GetFile(int planId)
        {
            var    plan     = db.HumDistributionPlans.Find(planId);
            string filepath = "C://CissaFiles//Plan.xls";//Server.MapPath("~/Doc/ExcelPlan.xls");

            using (var def = new XlsDef())
            {
                def.AddArea().AddRow().AddEmptyCell();
                var s = def.AddArea().AddRow();
                s.AddText("", 7);
                s.AddText("Утверждаю", 3);
                var s1 = def.AddArea().AddRow();
                s1.AddText("", 7);
                s1.AddText("Руководитель организации/Получатель", 3);
                var s3 = def.AddArea().AddRow();
                s3.AddText("", 7);
                s3.AddText("______________________", 3);
                var s4 = def.AddArea().AddRow();
                s4.AddText("", 7);
                s4.AddText("«    » _____________ 20___", 3);
                def.AddArea().AddRow().AddEmptyCell();
                var s5 = def.AddArea().AddRow();
                s5.AddText("План распределения гуманитарной помощи получателя \"" + plan.Company.Name + "\"", 10);
                s5.Style.HAlign = HAlignment.Center; //По центру
                s5.Style.Bold();
                var s6 = def.AddArea().AddRow();
                s6.Style.HAlign = HAlignment.Center; //По центру
                s6.AddText("Дата: " + plan.Date.Value.ToShortDateString(), 10);

                var h = def.AddArea().AddRow();
                h.AddText("№");
                h.AddText("Потребитель / Организация");
                h.AddText("Регион");
                h.AddText("Адрес");
                h.AddText("Наименование гум. помощи (товара)");
                h.AddText("Ед. изм.");
                h.AddText("Кол-во");
                h.AddText("Вес (кг)");
                h.AddText("Сумма (у.е.)");
                h.AddText("Примечание");
                h.ShowAllBorders(true);
                h.Style.FontStyle  = FontStyle.Bold;                //Шрифт жирный
                h.Style.HAlign     = HAlignment.Center;             //По центру
                h.Style.BgColor    = IndexedColors.BLUE_GREY.Index; //48; Цвет шапки
                h.Style.FontColor  = IndexedColors.WHITE.Index;     //Цвет шрифта
                h.Style.WrapText   = true;
                h.Style.AutoWidth  = true;
                h.Style.AutoHeight = true;
                int i = 1;
                foreach (var item in plan.Items)
                {
                    var r = def.AddArea().AddRow();
                    r.AddColumn().AddInt(i);
                    r.AddColumn().AddText(item.Consumer.Name);
                    r.AddColumn().AddText(item.Area.Name);
                    r.AddColumn().AddText(item.Address);
                    r.AddColumn().AddText(item.Product.Name);
                    r.AddColumn().AddText(item.UnitType.Name);
                    r.AddColumn().AddFloat(item.Amount ?? 0);
                    r.AddColumn().AddText("");
                    r.AddColumn().AddFloat((double)(item.Sum ?? 0));
                    r.AddColumn().AddText("");
                    r.ShowAllBorders(true);
                    i++;
                }
                var builder  = new XlsBuilder(def);
                var workbook = builder.Build();


                using (var stream = new FileStream(filepath, FileMode.Create))
                {
                    workbook.Write(stream);
                }
                return(File(filepath, "application/vnd.ms-excel", "Plan.xls"));
            }
        }