Заполнение шаблона Word - C#

Узнай цену своей работы

Формулировка задачи:

Помогите пожалуйста написать код. Есть окно в нем две формы (выпадающее меню, с фамилиями). Есть файл docx в котором нужно с помощью тех форм вбивать данные. Когда фамилии выбраны по кнопке ОК открывался отредактированный файл docx. Много лазил по интеренту но не смог найти рабочего решения моей задачи. По многим отзывам хотелось бы код с использованием open xml SDK. Помогите пожалуйста. Спасибо.

Решение задачи: «Заполнение шаблона Word»

textual
Листинг программы
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text.RegularExpressions;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using StorageLib;
 
namespace Utils
{
    public static class WordUtils
    {
        private const string FontFamily = "Times New Roman";
        public static void CreateDocument(string path, List<ResultEntity> results, IEnumerable<string> tasks)
        {
            using (var document = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document))
            {
                document.AddMainDocumentPart();
                document.MainDocumentPart.Document = new Document();
                var body = new Body();
                SetMargins(body);
                CreateHeader(body);
                FillBody(body, results, tasks);
                CreateFooter(body);
                document.MainDocumentPart.Document.AppendChild(body);
            }
        }
 
 
        private static void SetMargins(Body body)
        {
            var sectionProps = new SectionProperties();
            var pageMargin = new PageMargin
            {
                Top = FromMilimeters(220),
                Left = FromMilimeters(200),
                Right = FromMilimeters(100),
                Bottom = FromMilimeters(250)
            };
            sectionProps.AppendChild(pageMargin);
            body.AppendChild(sectionProps);
        }
 
        private static void CreateHeader(Body body)
        {
            CreatePreHeader(body);
            CreateHeader1(body);
            CreateHeader2(body);
            CreateHeader3(body);
        }
 
        private static void FillBody(Body body, ICollection<ResultEntity> results, IEnumerable<string> tasks)
        {
            CreateBody1(body, tasks);
            CreateBody2(body, results.Count);
            CreateBody3(body, results);
        }
 
 
        private static void CreatePreHeader(Body body)
        {
            string mask = string.Format(" __:__ __.__.{0} г", DateTime.Now.Year);
            string content1 = "sdgsdgsdg" + mask;
            string content2 = "sdgsdgsdg" + mask;
            const string content3 = "sdgsdgsdg";
            var run = new Run(ItalicRunPro,
                              new TabChar(), new Text(content1), new Break(),
                              new TabChar(), new Text(content2), new Break(),
                              new TabChar(), new Text(content3), new Break());
            var paragraph = new Paragraph(run);
            body.AppendChild(paragraph);
        }
 
 
        private static void CreateHeader1(Body body)
        {
            var firstR = new Run(BoldRunPro);
            firstR.Append(new Text("sdgsdgsd"), new Break(),
                          new Text("sdgsdgsdg"), new Break(),
                          new Text("(сил) на Восточном ТВД"));
            var firstPProp = new ParagraphProperties(
                new Justification { Val = JustificationValues.Center },
                HeaderIndentation,
                new ContextualSpacing { Val = true },
                new SpacingBetweenLines { LineRule = LineSpacingRuleValues.Exact, Line = FromMilimetersString(0) });
            var firstP = new Paragraph(firstPProp, firstR);
            body.AppendChild(firstP);
 
            var secondR = new Run(BoldRunPro);
            secondR.Append(new TabChar(), new Text("sggsdgsdg"));
            var secondPProp = new ParagraphProperties(
                HeaderIndentation,
                new ContextualSpacing { Val = true },
                new SpacingBetweenLines { LineRule = LineSpacingRuleValues.Exact, Line = FromMilimetersString(0) });//new ParagraphProperties(HeaderIndentation);
            var secondP = new Paragraph(secondPProp, secondR);
            body.AppendChild(secondP);
 
            var thirdR = new Run(BoldRunPro);
            thirdR.Append(new Text("some"), new Break());
            var thirdPProp = new ParagraphProperties(
                new Justification { Val = JustificationValues.Right },
                HeaderIndentation,
                new ContextualSpacing { Val = true },
                new SpacingBetweenLines { LineRule = LineSpacingRuleValues.Exact, Line = FromMilimetersString(0) });
            var thirdP = new Paragraph(thirdPProp, thirdR);
            body.AppendChild(thirdP);
        }
 
        private static void CreateHeader2(Body body)
        {
            var run = new Run(BoldRunPro);
            run.Append(new Break(),
                       new Text("ПРЕДЛОЖЕНИЯ"), new Break(),
                       new Text("sdgsdgsdg"), new Break(),
                       new Text("sgsdgsdgsdg"), new Break());
 
            var pProp = new ParagraphProperties(new Justification { Val = JustificationValues.Center });
            var paragraph = new Paragraph(pProp, run);
            body.AppendChild(paragraph);
        }
 
        private static void CreateHeader3(Body body)
        {
            const string content1 = "Иsdgsdg";
            const string content2 = "sdgsdgsdg";
            const string content3 = "sdgsdg"
            const string content4 = "sdgsdgsdg";
            var run = new Run(ItalicRunPro,
                new TabChar(), new Text(content1) { Space = SpaceProcessingModeValues.Preserve }, new Break(), new Break(),
                new TabChar(), new Text(content2) { Space = SpaceProcessingModeValues.Preserve }, new Break(),
                new TabChar(), new Text(content3) { Space = SpaceProcessingModeValues.Preserve }, new Break(), new Break(),
                new TabChar(), new Text(content4) { Space = SpaceProcessingModeValues.Preserve });
            var pProp = new ParagraphProperties(new LeftMargin { Width = FromMilimetersString(125) });
            var paragraph = new Paragraph(pProp, run);
            body.AppendChild(paragraph);
        }
 
        private static void CreateBody1(Body body, IEnumerable<string> focusTargets)
        {
            var run = new Run(ContentRunPro);
            var items = focusTargets.Select(s => new Text(s) {Space = SpaceProcessingModeValues.Preserve});
            foreach (var item in items)
            {
                run.AppendChild(new TabChar());
                run.AppendChild(item);
                run.AppendChild(new Break());
            }
            var pProp = new ParagraphProperties(new LeftMargin {Width = FromMilimetersString(125)});
            var paragraph = new Paragraph(pProp, run);
            body.AppendChild(paragraph);
        }
 
        private static void CreateBody2(Body body, int tasksCount)
        {
            const string content1 = "sdgsdg";
            const string content2 = " ПРЕДЛАГАЮ ";
            const string content3 = "gsdgsd {0} sdgsdg";
            var run1 = new Run(ContentRunPro, new TabChar(), new Text(content1));
            var run2 = new Run(BoldRunPro, new Text(content2) { Space = SpaceProcessingModeValues.Preserve });
            var run3 = new Run(ContentRunPro, new Text(string.Format(content3, tasksCount)));
            var pProp = new ParagraphProperties(new Justification { Val = JustificationValues.Left });
            var paragraph = new Paragraph(pProp, run1, run2, run3);
            body.AppendChild(paragraph);
        }
 
        private static void CreateBody3(Body body, IEnumerable<ResultEntity> results)
        {
            int i = 1;
            foreach (var result in results)
            {
                var rHead1 = new Run(ContentRunPro, new Text(i++ + ". " + "dgsdg"));
                var taskRun = new Run(BoldRunPro, new Text(" " + result.OZ.Trim() + " ") { Space = SpaceProcessingModeValues.Preserve });
                var rHead2 = new Run(ContentRunPro, new Text("sdgsdg"));
                var pEntryHeader = new Paragraph(rHead1, taskRun, rHead2);
                body.AppendChild(pEntryHeader);
 
                foreach (var pair in result.TasksAndActions)
                {
                    var rKey = new Run(ContentRunPro, new TabChar(), new Text("- ") { Space = SpaceProcessingModeValues.Preserve }, new Text(pair.Key));
                    var rActHeader = new Run(BoldRunPro, new Text(" sdgsdg ") { Space = SpaceProcessingModeValues.Preserve });
                    var rValue = new Run(ContentRunPro, new Text(pair.Value));
                    body.AppendChild(new Paragraph(ContentParPro, rKey, rActHeader, rValue));
                }
            }
        }
        private static void CreateFooter(Body body)
        {
            CreateFooter1(body);
            CreateFooter2(body);
        }
 
 
        private static void CreateFooter1(Body body)
        {
            const string content1 = "ПРОШУ:";
            const string content2 = "- строка1";
            const string content3 = "- строка2";
            var rFirstPart = new Run(BoldRunPro, new Break(), new TabChar(), new Text(content1), new Break());
            body.AppendChild(new Paragraph(rFirstPart));
 
            var rSecondPart = new Run(ContentRunPro, new Text(content2), new Break(), new Text(content3), new Break());
            body.AppendChild(new Paragraph(rSecondPart));
        }
        private static void CreateFooter2(Body body)
        {
            const string content1 = "футер";
            const string content2 = "футер2";
 
            var runHod = new Run(ContentRunPro, new Text(content1), new Break(), new Text(content2));
            var paragrah = new Paragraph(new ParagraphProperties(new Justification { Val = JustificationValues.Center }), runHod);
            body.AppendChild(paragrah);
        }
 
        #region support properties
 
        private static ParagraphProperties ContentParPro
        {
            get
            {
                return new ParagraphProperties(new Justification { Val = JustificationValues.Both });
            }
        }
        private static Indentation HeaderIndentation
        {
            get
            {
                return new Indentation {Left = FromMilimetersString(930)};
            }
        }
 
 
        private static RunProperties BoldRunPro
        {
            get
            {
                return new RunProperties(new RunFonts {HighAnsi = FontFamily, Ascii = FontFamily},
                                         new Bold {Val = new OnOffValue(true)},
                                         new FontSize {Val = new StringValue("28")});
            }
        }
 
        private static RunProperties ContentRunPro
        {
            get
            {
                return new RunProperties(new RunFonts {HighAnsi = FontFamily, Ascii = FontFamily},
                                         new FontSize {Val = new StringValue("28")});
            }
        }
 
        private static RunProperties ItalicRunPro
        {
            get
            {
                return new RunProperties(new RunFonts { HighAnsi = FontFamily, Ascii = FontFamily },
                                        new Italic { Val = new OnOffValue(true) },
                                         new FontSize { Val = new StringValue("28") });
            }
        }
 
        private static StringValue FromMilimetersString(int i)
        {
            return new StringValue(FromMilimeters(i).ToString());
        }
 
        private static ushort FromMilimeters(float value)
        {
            try
            {
                checked
                {
                    return (ushort) (value*5.67);
                }
            }
            catch
            {
                throw new ArgumentOutOfRangeException("value");
            }
        }
        #endregion
    }
}

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 4.4 из 5
Похожие ответы