Exemple #1
0
        private TableContent GetRequestInfosTableContent()
        {
            var rows = (IList <RequestApplicantInfoRecord>)TemplateFieldValueFactory
                       .Create(TemplateFieldName.RequestInfosOfDocument_Complex).Get(Parameters);

            var tableContent = new TableContent(nameof(RequestApplicantInfoRecord));

            if (rows.Any())
            {
                foreach (var row in rows)
                {
                    tableContent.AddRow(
                        new FieldContent(nameof(RequestApplicantInfoRecord.RequestNum), row.RequestNum),
                        new FieldContent(nameof(RequestApplicantInfoRecord.PatentName), row.PatentName),
                        new FieldContent(nameof(RequestApplicantInfoRecord.DeclarantShortInfo), row.DeclarantShortInfo)
                        );
                }
            }
            else
            {
                tableContent.AddRow(
                    new FieldContent(nameof(RequestApplicantInfoRecord.RequestNum), string.Empty),
                    new FieldContent(nameof(RequestApplicantInfoRecord.PatentName), string.Empty),
                    new FieldContent(nameof(RequestApplicantInfoRecord.DeclarantShortInfo), string.Empty)
                    );
            }


            return(tableContent);
        }
        static void GenFile()
        {
            var templateFileName = "template.docx";
            var tableContent     = new TableContent("row");

            tableContent.AddRow(new FieldContent("subject", "數學"), new FieldContent("score", "90"));
            tableContent.AddRow(new FieldContent("subject", "物理"), new FieldContent("score", "80"));

            var listContent = new ListContent("Team Members List")
                              .AddItem(
                new FieldContent("Name", "Eric"),
                new FieldContent("Role", "Program Manager"))
                              .AddItem(
                new FieldContent("Name", "Bob"),
                new FieldContent("Role", "Developer"));

            var nestLiest = new ListContent("NestedList")
                            .AddItem(new ListItemContent("Role", "Program Manager")
                                     .AddNestedItem(new FieldContent("Name", "Eric"))
                                     .AddNestedItem(new FieldContent("Name", "Ann")))
                            .AddItem(new ListItemContent("Role", "Developer")
                                     .AddNestedItem(new FieldContent("Name", "Bob"))
                                     .AddNestedItem(new FieldContent("Name", "Richard")));

            var imageContent = new ImageContent("Image", File.ReadAllBytes("cat.jpg"));

            var valuesToFill = new Content(new FieldContent("name", "王大明"), new FieldContent("avg", "85"), tableContent, listContent, nestLiest, imageContent);

            using var file             = new FileStream(templateFileName, FileMode.Open, FileAccess.Read);
            using var outputFileStream = new FileStream("output.docx", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            file.CopyTo(outputFileStream);
            using var ouputDocument = new TemplateProcessor(outputFileStream).SetRemoveContentControls(true);
            ouputDocument.FillContent(valuesToFill);
            ouputDocument.SaveChanges();
        }
Exemple #3
0
        private Content GetContent(List <ProjectReport> template, ApplicationUser user)
        {
            DateTime dateTime      = DateTime.Now;
            var      studentsTable = new TableContent("table");

            for (int i = 0; i < template.Count; i++)
            {
                studentsTable.AddRow(new FieldContent("employeeProjectName", template[i].Project.Name));
                for (int j = 0; j < template[i].Modules.Count; j++)
                {
                    studentsTable
                    .AddRow(
                        new FieldContent("employeeCount", j.ToString()),
                        new FieldContent("employeeModule", template[i].Modules[j].Module.Name),
                        new FieldContent("employeeProject", j.ToString()),
                        new FieldContent("employeeDate", j.ToString()),
                        new FieldContent("employeeCause", j.ToString()),
                        new FieldContent("employeeNote", j.ToString()));
                }
            }

            var valuesToFill = new Content(
                new FieldContent("reportName", "Отчет о выполненных задачах"),
                new FieldContent("reportDate", "За период с 01" + dateTime.Month.ToString() + dateTime.Year.ToString() + "по" + dateTime.Day.ToString() + dateTime.Year.ToString()),
                new FieldContent("employeePosition", user.Position.Name),
                new FieldContent("employeeQualification", user.QualificationLevel.Name),
                new FieldContent("date", DateTime.Now.Date.ToString()),
                studentsTable,
                new FieldContent("employeePositionTwo", user.Position.Name),
                new FieldContent("employeeName", user.UserName));

            return(valuesToFill);
        }
        private static Content PrepareProposalContent(ExcelFile excelFile, bool changeTemplateHeader)
        {
            var listTable        = new List <TableContent>();
            var listFieldContent = new List <FieldContent>();

            foreach (var workSheet in excelFile.Content)
            {
                switch (workSheet.Type)
                {
                case WorkSheetTypeEnum.Table:
                    var tableContent = new TableContent(workSheet.Name);
                    if (tableContent.Rows == null && changeTemplateHeader)
                    {
                        var arrayHeaderRow = new FieldContent[workSheet.HeaderRow.Cells.Count];
                        for (int column = 0; column < workSheet.HeaderRow.Cells.Count; column++)
                        {
                            arrayHeaderRow[column] = new FieldContent(workSheet.HeaderRow.Cells[column], workSheet.HeaderRow.Cells[column]);
                        }

                        tableContent.AddRow(arrayHeaderRow);
                    }

                    foreach (var row in workSheet.Rows)
                    {
                        var arrayRowField = new FieldContent[row.Cells.Count];
                        for (int column = 0; column < row.Cells.Count; column++)
                        {
                            arrayRowField[column] = new FieldContent(workSheet.HeaderRow.Cells[column], row.Cells[column]);
                        }

                        tableContent.AddRow(arrayRowField);
                    }

                    listTable.Add(tableContent);
                    break;

                case WorkSheetTypeEnum.Field:
                    foreach (var row in workSheet.Rows)
                    {
                        listFieldContent.Add(new FieldContent(row.Cells.FirstOrDefault(), row.Cells.LastOrDefault()));
                    }
                    break;

                default:
                    break;
                }
            }

            return(new Content
            {
                Tables = listTable,
                Fields = listFieldContent
            });
        }
Exemple #5
0
        private void buttonSave_Click(object sender, EventArgs e)
        {
            TableContent table = new TableContent("Extingushers");

            for (int i = 0; i < dataGridViewResult.RowCount - 1; i++)
            {
                table.AddRow(///TODO CORRECT CELLS
                    new FieldContent("Number", dataGridViewResult.Rows[i].Cells[3].Value.ToString()),
                    new FieldContent("Mark", dataGridViewResult.Rows[i].Cells[6].Value.ToString()),
                    new FieldContent("Concentration", dataGridViewResult.Rows[i].Cells[9].Value.ToString()),
                    new FieldContent("Expired", dataGridViewResult.Rows[i].Cells[dataGridViewResult.ColumnCount - 1].Value.ToString())
                    );
            }

            File.Delete("OutputDocument.docx");
            File.Copy("InputTemplate.docx", "OutputDocument.docx");

            var valuesToFill = new Content(
                new FieldContent("Report date", DateTime.Now.ToString()),
                table);

            using (var outputDocument = new TemplateProcessor("OutputDocument.docx")
                                        .SetRemoveContentControls(true))
            {
                outputDocument.FillContent(valuesToFill);
                outputDocument.SaveChanges();
            }
        }
        protected override Content GetContent()
        {
            var cardsTable = new TableContent("CardsTable");

            foreach (var card in _cards)
            {
                cardsTable.AddRow(new FieldContent("SideOne:Text", card.SideOne.Text), new FieldContent("SideTwo:Text", card.SideTwo.Text));
            }

            return(new Content(cardsTable));
        }
        public static TableContent AddTableActions(string tablePlaceholderName, List <Dictionary <string, Func <string> > > list)
        {
            var temp = new TableContent(tablePlaceholderName);

            foreach (var dict in list)
            {
                var items = AddSimpleActions(dict).ToArray();
                temp = temp.AddRow(items);
            }

            return(temp);
        }
Exemple #8
0
        protected virtual TableContent GetResearchesContent(IEnumerable <ResearchWork> works)
        {
            var researchesContent = new TableContent("ResearchWorkTable");

            foreach (var work in works)
            {
                researchesContent.AddRow(
                    new FieldContent("JobType", work.JobType.ValueOrDefault()),
                    new FieldContent("PresentationType", work.PresentationType.ValueOrDefault()),
                    new FieldContent("StartDate", work.StartDate?.ToShortDateString() ?? ""),
                    new FieldContent("FinishDate", work.FinishDate?.ToShortDateString() ?? ""));
            }

            researchesContent.AddRow(
                new FieldContent("JobType", ""),
                new FieldContent("PresentationType", ""),
                new FieldContent("StartDate", ""),
                new FieldContent("FinishDate", ""));

            return(researchesContent);
        }
Exemple #9
0
        private void btnReportAllEmployees_Click(object sender, EventArgs e)
        {
            string       mainDate   = getMainDate();
            DataTable    employees  = database.getEmployeesForReport();
            TableContent tableEvent = new TableContent("Team Members");
            int          length     = employees.Rows.Count;

            foreach (DataRow dtRow in employees.Rows)
            {
                string personalNumber = dtRow["personal_number"].ToString();
                string name           = dtRow["name"].ToString();
                string surname        = dtRow["surname"].ToString();
                //string patronymic = dtRow["patronymic"].ToString();
                string positionName   = dtRow["positionName"].ToString();
                string departmentName = dtRow["departmentName"].ToString();


                tableEvent.AddRow(
                    new FieldContent("personalNumber", personalNumber),
                    new FieldContent("Full Name", surname + " " + name),
                    new FieldContent("Role", positionName),
                    new FieldContent("department", departmentName)
                    );
            }

            string employeeWord = GetDeclension(length, "сотрудник", "сотрудника", "сотрудников");
            var    valuesToFill = new TemplateEngine.Docx.Content(
                tableEvent,
                new FieldContent("Report date", mainDate),
                new FieldContent("Count", length.ToString() + " " + employeeWord)
                );

            string destinationFolderPath = @"D:\Documents\Отчеты о составе команды";
            string templatePath          = @"D:\Documents Templates\Отчет о сотрудниках.docx";
            string newFilePath           = @"D:\Documents\Отчеты о составе команды\Отчет о составе команды от " + mainDate + ".docx";

            if (!Directory.Exists(destinationFolderPath))
            {
                Directory.CreateDirectory(destinationFolderPath);
            }

            File.Delete(newFilePath);
            File.Copy(templatePath, newFilePath);

            using (var outputDocument = new TemplateProcessor(newFilePath)
                                        .SetRemoveContentControls(true))
            {
                outputDocument.FillContent(valuesToFill);
                outputDocument.SaveChanges();
            }
            Process.Start(newFilePath);
        }
Exemple #10
0
        private TableContent CreateAssessmentByDisciplinesTable3(AssessmentByDiscipline[] assessmentByDisciplines)
        {
            var tableContent = new TableContent("AssessmentByDisciplines");

            foreach (var assessmentByDiscipline in assessmentByDisciplines.Where(ass => ass.ControlType == ControlType.StateExam))
            {
                tableContent.AddRow(
                    new FieldContent("NameOfStateExam", assessmentByDiscipline.NameOfDiscipline),
                    new FieldContent("Assessment3", typeof(Assessment).GetField(assessmentByDiscipline.Assessment.ToString()).GetCustomAttribute <NameEnumValueAttribute>().NameEnumValue.ToLower()));
            }

            return(tableContent);
        }
    public void MakeReport(string reportFileName, string sourceDirectoryName, ICreateReportOptions options)
    {
        var di = new DirectoryInfo(sourceDirectoryName);

        if (!di.Exists)
        {
            throw new DirectoryNotFoundException(sourceDirectoryName);
        }

        var fi = new FileInfo(reportFileName);

        if (fi.Exists)
        {
            fi.Delete();
        }

        File.Copy(reportTemplate, reportFileName);

        var tableContent = new TableContent("Files");

        foreach (var fileInfo in di.GetFiles())
        {
            tableContent.AddRow(
                new FieldContent("FileName", fileInfo.Name),
                new FieldContent("FileSize", fileInfo.Length.ToString()));
        }

        var valuesToFill = new Content(
            new FieldContent("DirectoryName", di.Name),
            new FieldContent("DirectoryPath", di.Parent.FullName),
            tableContent
            );

        using (var outputDocument = new TemplateProcessor(reportFileName)
                                    .SetRemoveContentControls(true))
        {
            outputDocument.FillContent(valuesToFill);
            outputDocument.SaveChanges();
        }

        if (options.OpenAfterCreate)
        {
            ProcessStartInfo info = new ProcessStartInfo()
            {
                FileName        = reportFileName,
                UseShellExecute = true
            };

            Process.Start(info);
        }
    }
Exemple #12
0
        private TableContent CreateAssessmentByDisciplinesTable2(AssessmentByDiscipline[] assessmentByDisciplines, DisciplineExtendedProxy[] disciplines)
        {
            var tableContent = new TableContent("AssessmentByDisciplines");

            foreach (var assessmentByDiscipline in assessmentByDisciplines.Where(ass => ass.ControlType == ControlType.Practice))
            {
                tableContent.AddRow(
                    new FieldContent("NameOfPractice", assessmentByDiscipline.NameOfDiscipline),
                    new FieldContent("ClassHours2", GetClassHours(assessmentByDiscipline, disciplines).ToString()),
                    new FieldContent("Assessment2", typeof(Assessment).GetField(assessmentByDiscipline.Assessment.ToString()).GetCustomAttribute <NameEnumValueAttribute>().NameEnumValue.ToLower()));
            }

            return(tableContent);
        }
        protected virtual TableContent GenerateExamsContent(IEnumerable <ExamInfo> exams)
        {
            var examsData = new TableContent("ExamsData");

            foreach (var exam in exams)
            {
                examsData.AddRow(
                    new FieldContent("FullName", exam.Discipline?.FullName ?? ""),
                    new FieldContent("Mark", exam.Mark.ToString()),
                    new FieldContent("Date", exam.Date?.ToShortDateString() ?? "")
                    );
            }

            return(examsData);
        }
Exemple #14
0
        public async Task <IActionResult> PrintAsync([FromRoute] string doctorId, [FromQuery] DateTime startDate, [FromQuery] DateTime endDate, [FromQuery] string format)
        {
            var appointments = await _dbContext.Appointments.Where(x => x.EmployeeId == doctorId && x.Status == AppointmentStatuses.FINISHED && x.DateTime >= startDate && x.DateTime <= endDate).Include(x => x.Patient)
                               .Include(x => x.Employee).ThenInclude(x => x.Organization).Include(x => x.Actions)
                               .ThenInclude(x => x.Coding).Include(x => x.Reasons).ThenInclude(x => x.Coding)
                               .Include(x => x.Diagnosis).ThenInclude(x => x.Code).OrderBy(x => x.DateTime).ToListAsync();

            var printServiceClient = _httpClientFactory.CreateClient();

            printServiceClient.BaseAddress = new Uri("http://localhost:54481");
            var tableContent = new TableContent("Tickets");
            var i            = 0;

            foreach (var appointment in appointments)
            {
                i++;
                var fields = new List <IContentItem>
                {
                    new FieldContent("Ticket.№", i.ToString()),
                    new FieldContent("Ticket.VisitedAt", appointment.DateTime.ToString("dd.MM.yyyy HH:mm")),
                    new FieldContent("Ticket.Сount", "1"),
                    new FieldContent("Ticket.Patients.FIO", $"{appointment.Patient.LastName} {appointment.Patient.FirstName} {appointment.Patient.MiddleName}"),
                    new FieldContent("Ticket.Sex", appointment.Patient.Gender == "MALE"?"Чоловіча":"Жіноча"),
                    new FieldContent("Ticket.Patients.BirthDate", appointment.Patient.BirthDate.ToString("dd.MM.yyyy")),
                    new FieldContent("Ticket.Patients.Phone", appointment.Patient.Phone),
                    new FieldContent("Ticket.Cause", string.Join(", ", appointment.Reasons.Select(x => x.Coding.Code))),
                    new FieldContent("Ticket.Diagnosis", appointment.Diagnosis.Code.Code),
                    new FieldContent("Ticket.Process", string.Join(", ", appointment.Actions.Select(x => x.Coding.Code))),
                };
                tableContent.AddRow(fields.ToArray());
            }

            var content = new Container(tableContent);
            // content.Fields.Add(new FieldContent("ORG","aaaaaaa"));
            // content.Tables.Add();
            var serializedContent = JsonConvert.SerializeObject(content);
            var stringContent     =
                new StringContent(serializedContent, Encoding.UTF8, "application/json");
            var response = await printServiceClient.PostAsync(new Uri($"api/Print/v2/f074_o_v2?responseType={format}", UriKind.Relative),
                                                              stringContent);

            if (!response.IsSuccessStatusCode)
            {
                return(StatusCode((int)response.StatusCode, await response.Content.ReadAsStringAsync()));
            }
            Response.Headers.TryAdd("Content-Disposition", $"inline; filename=\"appointments.docx\"");
            return(File(await response.Content.ReadAsStreamAsync(), response.Content.Headers.ContentType.MediaType));
        }
        protected virtual TableContent GenerateScienceActivities(IEnumerable <ScienceActivity> activities)
        {
            var activitiesData = new TableContent("ScienceActivity");

            foreach (var activity in activities)
            {
                activitiesData.AddRow(
                    new FieldContent("Title", activity.Title.ValueOrDefault()),
                    new FieldContent("PlanResult", activity.PlanResult.ValueOrDefault()),
                    new FieldContent("StartDate", activity.StartDate?.ToShortDateString() ?? ""),
                    new FieldContent("FinishDate", activity.FinishDate?.ToShortDateString() ?? "")
                    );
            }

            return(activitiesData);
        }
Exemple #16
0
        private TableContent CreateTableContent(List <Выполненная_услуга> услуги)
        {
            TableContent tc      = new TableContent("_строка");
            int          counter = 0;

            foreach (Выполненная_услуга у in услуги)
            {
                tc.AddRow(new FieldContent("№", (++counter).ToString()),
                          new FieldContent("наименование", у.наименование),
                          new FieldContent("количество", у.количество.ToString()),
                          new FieldContent("едизм", у.ед_изм),
                          new FieldContent("цена", у.цена.ToString()),
                          new FieldContent("сумма", у.сумма.ToString()));
            }

            return(tc);
        }
        protected virtual TableContent GenerateCalendarReport(IEnumerable <CalendarStage> stages)
        {
            int index = 1;

            var plansContent = new TableContent("CalendarPlanResults");

            foreach (var stage in stages)
            {
                plansContent.AddRow(
                    new FieldContent("Index", index.ToString()),
                    new FieldContent("StageName", stage.StageName.ValueOrDefault()),
                    new FieldContent("OutcomeResult", stage.OutcomeResult.ValueOrDefault())
                    );

                index++;
            }

            return(plansContent);
        }
Exemple #18
0
        private Content GetContent(List <Department> departments)
        {
            var studentsTable = new TableContent("departmentTable");

            for (int i = 0; i < departments.Count; i++)
            {
                studentsTable.AddRow(
                    new FieldContent("departmentId", departments[i].Id.ToString()),
                    new FieldContent("departmentName", departments[i].Name),
                    new FieldContent("departmentFacultyName", departments[i].Faculty.Name));
            }
            var valuesToFill = new Content(
                new FieldContent("name", "Department"),
                studentsTable,
                new FieldContent("count", departments.Count.ToString()),
                new FieldContent("date", DateTime.Now.Date.ToString()));

            return(valuesToFill);
        }
Exemple #19
0
        // Метод для строки
        private TableContent TableTemplateContent()
        {
            var rows = (IList <RequestApplicantInfoRecord>)TemplateFieldValueFactory
                       .Create(TemplateFieldName.RequestApplicantInfoRecords_Complex).Get(Parameters);

            var tableContent = new TableContent("RequestNTable");


            //List<string> rowsQ = new List<string>();
            //rowsQ.Add(TemplateFieldValueFactory
            //    .Create(TemplateFieldName.RequestNumber).Get(Parameters));
            //var rowIndex = 0;
            //foreach (var tableRow in rows)
            //{
            //    tableContent.AddRow(
            //        new FieldContent("RequestNum", tableRow.RequestNum),
            //        new FieldContent("Declarants", tableRow.Declarant),
            //        new FieldContent("RequestDate", tableRow.RequestDate.ToString()),
            //        new FieldContent("RowIncrement", (++rowIndex).ToString())
            //    );
            //}


            for (var i = 0; i < rows.Count; i++)

            {
                var tableRow = rows[i];


                tableContent.AddRow(
                    new FieldContent("RequestNum", tableRow.RequestNum),
                    new FieldContent("DeclarantShortInfo", tableRow.DeclarantShortInfo),
                    new FieldContent("RowIncrement", (i + 1).ToString()),
                    new FieldContent("RequestDate", tableRow.RequestDate)


                    );
            }

            return(tableContent);
        }
        protected virtual TableContent GenerateCalendarPlan(IEnumerable <CalendarStage> stages)
        {
            int index = 1;

            var stagesData = new TableContent("CalendarPlan");

            foreach (var stage in stages)
            {
                stagesData.AddRow(
                    new FieldContent("Index", index.ToString()),
                    new FieldContent("StageName", stage.StageName.ValueOrDefault()),
                    new FieldContent("StartDate", stage.StartDate?.ToShortDateString() ?? ""),
                    new FieldContent("FinishDate", stage.FinishDate?.ToShortDateString() ?? ""),
                    new FieldContent("WaitResult", stage.WaitResult.ValueOrDefault())
                    );

                index++;
            }

            return(stagesData);
        }
Exemple #21
0
        private TableContent ConstructTableContent <TRow>(DocumentTable <TRow> table) where TRow : class
        {
            var tableContent = new TableContent(table.TableKey);
            var members      = GetModelMembers(typeof(TRow));

            foreach (var row in table.Rows)
            {
                var rowItems = new List <IContentItem>();
                foreach (var member in members)
                {
                    var value = member.GetValue <string>(row);
                    if (value != null)
                    {
                        rowItems.Add(new FieldContent(member.Name, value));
                    }
                }
                tableContent.AddRow(rowItems.ToArray());
            }

            return(tableContent);
        }
Exemple #22
0
        private void buttonSave_Click(object sender, EventArgs e)
        {
            //Открываем диалог сохранения файла
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            //Создаем объект, отвечающий за таблицы в отчете
            TableContent table = new TableContent("Extingushers");

            for (int i = 0; i < dataGridViewResult.RowCount - 1; i++)
            {
                //Заполняем эту таблицу, создавая объекты, отвечающие за метки в отчете
                table.AddRow(///TODO CORRECT CELLS
                    new FieldContent("Number", dataGridViewResult.Rows[i].Cells[3].Value.ToString()),
                    new FieldContent("Mark", dataGridViewResult.Rows[i].Cells[6].Value.ToString()),
                    new FieldContent("Concentration", dataGridViewResult.Rows[i].Cells[9].Value.ToString()),
                    new FieldContent("Expired", dataGridViewResult.Rows[i].Cells[dataGridViewResult.ColumnCount - 1].Value.ToString())
                    );
            }
            //Удаляем старый файл, если он есть
            File.Delete(saveFileDialog.FileName);
            //Копируем на его место шаблон
            File.Copy("InputTemplate.docx", saveFileDialog.FileName);

            //Обозначем, какими данными заполним шаблон
            var valuesToFill = new Content(
                new FieldContent("Report date", DateTime.Now.ToString()),
                table);

            //Заполняем шаблон, убирая метки
            using (var outputDocument = new TemplateProcessor(saveFileDialog.FileName)
                                        .SetRemoveContentControls(true))
            {
                outputDocument.FillContent(valuesToFill);
                outputDocument.SaveChanges();
            }
        }
        protected void downloadFile_btn_OnClick(object sender, EventArgs e)
        {
            var    targetPath = "D:/demo/";
            string fileName   = $"{DateTime.Now:yyyyMMddHHmmss}.docx";

            File.Copy(Server.MapPath("~/Template/template.docx"), targetPath + fileName);

            var valuesToFill = new Content();

            valuesToFill.Fields.Add(new FieldContent("name", "王小明"));
            valuesToFill.Fields.Add(new FieldContent("special_1", "■"));
            valuesToFill.Fields.Add(new FieldContent("special_2", "□"));

            var tableContent = new TableContent("row");

            foreach (var f in FakeData())
            {
                tableContent.AddRow(
                    new FieldContent("r_name", f.Name),
                    new FieldContent("r_chinese", f.Chinese),
                    new FieldContent("r_english", f.English),
                    new FieldContent("r_math", f.Math)
                    );
            }
            valuesToFill.Tables.Add(tableContent);
            var avg_chinese = FakeData().Average(x => Convert.ToDecimal(x.Chinese));
            var avg_english = FakeData().Average(x => Convert.ToDecimal(x.English));
            var avg_math    = FakeData().Average(x => Convert.ToDecimal(x.Math));

            valuesToFill.Fields.Add(new FieldContent("avg_chinese", avg_chinese.ToString("0.0")));
            valuesToFill.Fields.Add(new FieldContent("avg_english", avg_english.ToString("0.0")));
            valuesToFill.Fields.Add(new FieldContent("avg_math", avg_math.ToString("0.0")));

            using (var outputDocument = new TemplateProcessor(targetPath + fileName).SetRemoveContentControls(true))
            {
                outputDocument.FillContent(valuesToFill);
                outputDocument.SaveChanges();
            }
        }
Exemple #24
0
        public void Export()
        {
            this.setViewModel();
            var fileInfo    = new FileInfo(_viewModel.TemplatePath);
            var newFileInfo = new FileInfo(fileInfo.DirectoryName + "\\" + fileInfo.Name.Split('.')[0] + "_new" + fileInfo.Extension);

            File.Delete(newFileInfo.FullName);
            File.Copy(fileInfo.FullName, newFileInfo.FullName);

            using (var outputDocument = new TemplateProcessor(newFileInfo.FullName).SetRemoveContentControls(true)) {
                ListContent listContent = new ListContent("Table list");
                foreach (var t in _viewModel.Tables)
                {
                    var listItemContent = new ListItemContent();
                    listContent.AddItem(listItemContent);
                    listItemContent.AddField("Table title", "[" + t.Schema + "].[" + t.TableName + "]");
                    listItemContent.AddField("Table name", "[" + t.Schema + "].[" + t.TableName + "]");
                    listItemContent.AddField("Table description", t.Description);
                    listItemContent.AddField("Table pk", t.PrimaryKeys);

                    var columnContent = new TableContent("Column row");
                    listItemContent.AddTable(columnContent);
                    foreach (var c in t.Columns)
                    {
                        columnContent.AddRow(
                            new FieldContent("Name", c.Name),
                            new FieldContent("Type", c.Type),
                            new FieldContent("Null", c.Nullable),
                            new FieldContent("Description", c.Description));
                    }
                }

                Content mainContent = new Content(listContent);
                outputDocument.FillContent(mainContent);
                outputDocument.SaveChanges();
            }
        }
Exemple #25
0
        public void CreateWordFileReport(List <CollectInternalData> expencesData, List <CollectInternaIncomelData> incomeData)
        {
            File.Delete("OutputDocument.docx");
            File.Copy("InputTemplate.docx", "OutputDocument.docx");

            var tableContent       = new TableContent("Expences Table");
            var incomeTableContent = new TableContent("Income Table");
            int number             = 1;

            foreach (var expence in expencesData)
            {
                tableContent.AddRow(
                    new FieldContent("Number", number.ToString()),
                    new FieldContent("Time", expence.Data.TransactionTime.ToString()),
                    new FieldContent("Amount", expence.Data.TransactionAmount.ToString()),
                    new FieldContent("Spend on", expence.Data.TransactionReceived),
                    new FieldContent("Type", expence.Data.TransactionType));
            }

            foreach (var income in incomeData)
            {
                incomeTableContent.AddRow(
                    new FieldContent("Number", number.ToString()),
                    new FieldContent("Time", income.Data.Time.ToString()),
                    new FieldContent("Amount", income.Data.Amount.ToString()),
                    new FieldContent("Source", income.Data.Source),
                    new FieldContent("Type", income.Data.Type));
            }
            var valuesToFill = new Content(tableContent, incomeTableContent);

            using (var outputDocument = new TemplateProcessor("OutputDocument.docx")
                                        .SetRemoveContentControls(true))
            {
                outputDocument.FillContent(valuesToFill);
                outputDocument.SaveChanges();
            }
        }
Exemple #26
0
        private void Create_Doc(object sender, RoutedEventArgs e)
        {
            string  file   = AppDomain.CurrentDomain.BaseDirectory + "/tempplates/nak.docx";
            Content values = new Content();

            values.Fields.Add(new FieldContent("data", DateTime.Now.ToShortDateString().ToString()));
            values.Lists.Add(new ListContent("List"));
            ListContent ll = values.Lists.First();

            for (int i = 0; i < all.Length; i++)
            {
                TableContent tt       = new TableContent("table");
                ArrayList    tmp      = all[i] as ArrayList;
                double       allprice = 0;
                for (int j = 0; j < tmp.Count; j++)
                {
                    Row tmprow = (Row)all[i][j];
                    int count  = (int)counts[i][j];
                    tt.AddRow(new FieldContent("nameD", tmprow.name), new FieldContent("Mater", tmprow.material), new FieldContent("Size", tmprow.size), new FieldContent("Count", count + ""), new FieldContent("Price", tmprow.price + ""), new FieldContent("allPrice", tmprow.price * count + ""));
                    allprice += tmprow.price * count;
                }
                ll.AddItem(new FieldContent("N", (i + 1) + ""), tt, new FieldContent("all", allprice + ""));
            }
            Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
            saveFileDialog.DefaultExt = "docx";
            saveFileDialog.Filter     = "Docx|*.docx";
            if (saveFileDialog.ShowDialog() == true)
            {
                File.Copy(file, saveFileDialog.FileName);
                using (var outputDocument = new TemplateProcessor(saveFileDialog.FileName)
                                            .SetRemoveContentControls(true))
                {
                    outputDocument.FillContent(values);
                    outputDocument.SaveChanges();
                }
            }
        }
        protected virtual Content GenerateWorkPlan(WorkPlan plan)
        {
            var stages  = new TableContent("WorkPlan");
            var content = new Content(
                new FieldContent("WorkPlanAdviserApproveDate", plan.AdviserApproveDate?.ToShortDateString() ?? ""),
                new FieldContent("WorkPlanSubmitDate", plan.SubmitDate?.ToShortDateString() ?? ""),
                new FieldContent("FinalCertification", plan.FinalCertification ?? ""),
                new FieldContent("CouncilNumber", plan.CouncilNumber ?? "")
                );

            foreach (var stage in plan.WorkStages)
            {
                stages.AddRow(
                    new FieldContent("JobInfo", stage.JobInfo.ValueOrDefault()),
                    new FieldContent("StartDate", stage.StartDate?.ToShortDateString() ?? ""),
                    new FieldContent("FinishDate", stage.FinishDate?.ToShortDateString() ?? ""),
                    new FieldContent("Note", stage.Note.ValueOrDefault())
                    );
            }

            content.Tables.Add(stages);

            return(content);
        }
Exemple #28
0
        public override CustomFile ProceedCV(string templatePath, CVExportModel cvModel)
        {
            using (MemoryStream mem = new MemoryStream(File.ReadAllBytes(templatePath)))
            {
                using (var outputDocument = new TemplateProcessor(mem)
                                            .SetRemoveContentControls(true))
                {
                    var valuesToFill = new Content(
                        new FieldContent("FullName", cvModel.FullName),
                        new FieldContent("Qualification", cvModel.Qualification),
                        new FieldContent("Summary", cvModel.Summary)
                        );

                    ListContent skillsList = new ListContent("Skills Nested List");
                    foreach (var technology in cvModel.Technologies)
                    {
                        ListItemContent technologyListItem = new ListItemContent("Technology", technology.Name);
                        ListContent     skillItem          = new ListContent("Skill");
                        foreach (var skill in technology.Skills)
                        {
                            skillItem.AddItem(
                                new FieldContent("SkillName", skill.Name),
                                new FieldContent("KnowledgeLevel", skill.KnowledgeLevel));
                        }
                        technologyListItem.AddList(skillItem);
                        skillsList.AddItem(technologyListItem);
                    }
                    valuesToFill.Lists.Add(skillsList);

                    TableContent experienceTable = new TableContent("ExperienceTable");
                    foreach (var jobExperienceModel in cvModel.JobExperiences)
                    {
                        experienceTable.AddRow(
                            new FieldContent("Company", jobExperienceModel.Company),
                            new FieldContent("Project", jobExperienceModel.Project),
                            new FieldContent("ProjectDescription", jobExperienceModel.Description),
                            new FieldContent("Period", jobExperienceModel.Period),
                            new FieldContent("Space", string.Empty));
                    }
                    valuesToFill.Tables.Add(experienceTable);

                    TableContent educationTable = new TableContent("EducationTable");
                    foreach (var educationModel in cvModel.Educations)
                    {
                        educationTable.AddRow(
                            new FieldContent("Place", educationModel.Place),
                            new FieldContent("Speciality", educationModel.Speciality),
                            new FieldContent("Degree", educationModel.Degree),
                            new FieldContent("Period", educationModel.Period),
                            new FieldContent("Space", string.Empty));
                    }
                    valuesToFill.Tables.Add(educationTable);

                    outputDocument.SetNoticeAboutErrors(false);
                    outputDocument.FillContent(valuesToFill);
                    outputDocument.SaveChanges();

                    _filecontents = mem.ToArray();

                    return(this);
                }
            }
        }
Exemple #29
0
        public static void FillContentControls(string fileName, List <DocumentData> newDocumentDatas)
        {
            List <IContentItem> contentItems = new List <IContentItem>();

            foreach (var item in newDocumentDatas)
            {
                if (item is FieldDocumentData)
                {
                    contentItems.Add(new FieldContent((item as FieldDocumentData).Key, (item as FieldDocumentData).Value));
                }

                if (item is ListDocumentData)
                {
                    ListContent listContent = new ListContent(item.Key);

                    if ((item as ListDocumentData).Fields.Count != 0)
                    {
                        for (int i = 0; i < (item as ListDocumentData).Fields[0].Values.Count; i++)
                        {
                            ListItemContent listcontentItems = new ListItemContent();

                            foreach (var item1 in (item as ListDocumentData).Fields)
                            {
                                listcontentItems.AddField((item1 as FieldsDocumentData).Key, (item1 as FieldsDocumentData).Values[i]);
                            }

                            foreach (var item1 in (item as ListDocumentData).Tables)
                            {
                                TableContent tableContent = new TableContent(item1.Key);

                                if ((item1 as TableDocumentData).Fields.Count != 0)
                                {
                                    for (int j = ((item1 as TableDocumentData).Fields[0].Values.Count / (item as ListDocumentData).Fields[0].Values.Count) * i; j < ((item1 as TableDocumentData).Fields[0].Values.Count / (item as ListDocumentData).Fields[0].Values.Count) + (((item1 as TableDocumentData).Fields[0].Values.Count / (item as ListDocumentData).Fields[0].Values.Count) * i); j++)
                                    {
                                        List <IContentItem> tableRowContent = new List <IContentItem>();

                                        foreach (var item2 in (item1 as TableDocumentData).Fields)
                                        {
                                            tableRowContent.Add(new FieldContent((item2 as FieldsDocumentData).Key, (item2 as FieldsDocumentData).Values[j]));
                                        }

                                        tableContent.AddRow(tableRowContent.ToArray());
                                    }
                                }

                                listcontentItems.AddTable(tableContent);
                            }

                            listContent.AddItem(listcontentItems);
                        }
                    }

                    contentItems.Add(listContent);
                }

                if (item is TableDocumentData)
                {
                    TableContent tableContent = new TableContent(item.Key);

                    if ((item as TableDocumentData).Fields.Count != 0)
                    {
                        for (int i = 0; i < (item as TableDocumentData).Fields[0].Values.Count; i++)
                        {
                            List <IContentItem> tableRowContent = new List <IContentItem>();

                            foreach (var item1 in (item as TableDocumentData).Fields)
                            {
                                tableRowContent.Add(new FieldContent((item1 as FieldsDocumentData).Key, (item1 as FieldsDocumentData).Values[i]));
                            }

                            tableContent.AddRow(tableRowContent.ToArray());
                        }
                    }

                    contentItems.Add(tableContent);
                }
            }

            var valuesToFill = new Content(contentItems.ToArray());

            using (var outputDocument = new TemplateProcessor(fileName).SetRemoveContentControls(true))//true false
            {
                outputDocument.FillContent(valuesToFill);
                outputDocument.SaveChanges();
            }
        }
        public ActionResult genDn(PlatForDNView platList)
        {
            nemo_freshEntities db = new nemo_freshEntities();

            if (platList == null)
            {
                return(Json(new JsonResponseModel("Error", "No dn"), JsonRequestBehavior.AllowGet));
            }

            TableContent t1         = new TableContent("OurActionsTable");
            int          i_servises = 1;

            foreach (var a in platList.Payments)
            {
                if (a.PurOfPayment != null || a.PurOfPayment.Length != 0)
                {
                    t1.AddRow(
                        new FieldContent("Num", i_servises++.ToString() ?? ""),
                        new FieldContent("ActionDescr", a.PurOfPayment),
                        new FieldContent("Sum", a.sum != null ? String.Format("{0:f2}", a.sum) : "")
                        );
                }
            }

            var valuesToFill = new Content(t1, new FieldContent("Total", String.Format("{0:f2}", platList.SelectedSum))

                                           );

            var newNameFolder = Properties.Resources.DiscLetter + @"\DNDocs\";
            // var newNameFolder = @"C:\DNDocs\Plat\";
            var newNameDoc = "PatentRegistry.docx";

            if (!Directory.Exists(newNameFolder))
            {
                Directory.CreateDirectory(newNameFolder);
            }
            string fullPathFile = newNameFolder + newNameDoc;

            int    count        = 1;
            string fileNameOnly = Path.GetFileNameWithoutExtension(fullPathFile);
            string extension    = Path.GetExtension(fullPathFile);
            string path         = Path.GetDirectoryName(fullPathFile);
            string newFullPath  = fullPathFile;

            while (System.IO.File.Exists(newFullPath))
            {
                string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
                newFullPath  = Path.Combine(path, tempFileName + extension);
                fullPathFile = newFullPath;
            }


            var templatePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "DnTemplates/RegistrPlat.docx";

            System.IO.File.Copy(templatePath, fullPathFile, true);
            using (var outputDoc = new TemplateProcessor(fullPathFile).SetRemoveContentControls(true))
            {
                outputDoc.FillContent(valuesToFill);
                outputDoc.SaveChanges();
            }
            // var doc = DocumentsGetter.GetDnDocument(dn.No, Url.Content("~"), fullPathFile);

            db.SaveChanges();

            var doc = DocumentGetter.GetDnDocument("8888", Url.Content("~"), fullPathFile);

            return(Json(new JsonResponseModel("Ok", "")
            {
                Doc = doc
            }, JsonRequestBehavior.AllowGet));
            //return "OK";
        }