コード例 #1
0
        public void createCustomStyle(Word.Application myWordApp, Word.Document myWordDocument, string name) //incomplete
        {
            Style sectionHeadingExt = myWordDocument.Styles.Add(name);

            //sectionHeadingExt.set_BaseStyle(SectionHeadingInt);
            sectionHeadingExt.Font.Size  = 14;
            sectionHeadingExt.Font.Color = WdColor.wdColorBlack;
            sectionHeadingExt.Font.Bold  = (int)MsoTriState.msoFalse;
            sectionHeadingExt.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceMultiple;
            sectionHeadingExt.ParagraphFormat.LineSpacing     = myWordApp.LinesToPoints((float)1.11);
            sectionHeadingExt.ParagraphFormat.SpaceBefore     = 0;
            sectionHeadingExt.ParagraphFormat.SpaceAfter      = 0;
            myWordApp.Selection.set_Style("myStyle");
        }
コード例 #2
0
ファイル: MainForm.cs プロジェクト: BesuglovS/Session
        private void SaveAsWordDocument()
        {
            DateTime beginSessionDate, endSessionDate;
            DetectSessionDates(out beginSessionDate, out endSessionDate);

            object oMissing = System.Reflection.Missing.Value;
            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

            //Start Word and create a new document.

            Word._Application oWord = new Word.Application();
            oWord.Visible = true;
            Word._Document oDoc =
                oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1);
            oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1);
            oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1);
            oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1);

            var faculties = _sRepo.GetAllFaculties();

            for (int facCounter = 0; facCounter < Constants.Constants.facultyGroups.Keys.Count; facCounter++)
            {
                var groupIds = new List<int>();

                foreach (var group in Constants.Constants.facultyGroups.ElementAt(facCounter).Value)
                {
                    var groupId = _sRepo.FindStudentGroup(group);
                    if (groupId != null)
                    {
                        groupIds.Add(groupId.StudentGroupId);
                    }
                }

                var facultyExams = _repo.GetFacultyExams(_sRepo, groupIds);

                facultyExams = facultyExams.OrderBy(fe => fe.Key).ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);

                Word.Paragraph oPara1 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara1.Range.Font.Size = 24;
                oPara1.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara1.Range.Text = "Расписание";
                oPara1.Format.SpaceAfter = 0;
                oPara1.Range.InsertParagraphAfter();

                oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara1.Range.Font.Size = 14;
                oPara1.Format.SpaceAfter = 0;
                if (beginSessionDate.Month < 3)
                {
                    var startYear = beginSessionDate.Year - 1;
                    oPara1.Range.Text = "зимней сессии " + startYear + "-" + (startYear + 1) + " учебного года" +
                        Environment.NewLine + Constants.Constants.facultyTitles[facCounter];
                }
                else
                {
                    var startYear = beginSessionDate.Year - 1;
                    oPara1.Range.Text = "летней сессии " + startYear + "-" + (startYear + 1) + " учебного года" +
                        Environment.NewLine + Constants.Constants.facultyTitles[facCounter];
                }
                oPara1.Range.InsertParagraphAfter();

                Word.Shape signBox = oDoc.Shapes
                    .AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 350, 15, 200, 75, oPara1.Range);

                signBox.Line.Visible = MsoTriState.msoFalse;
                signBox.TextFrame.ContainingRange.ParagraphFormat.Alignment =
                    Word.WdParagraphAlignment.wdAlignParagraphRight;

                signBox.TextFrame.ContainingRange.InsertAfter("«УТВЕРЖДАЮ»");
                signBox.TextFrame.ContainingRange.InsertParagraphAfter();
                signBox.TextFrame.ContainingRange.InsertAfter("Проректор по учебной работе");
                signBox.TextFrame.ContainingRange.InsertParagraphAfter();
                signBox.TextFrame.ContainingRange.InsertAfter("____________  А.В. Синицкий");

                var groups = Constants.Constants.facultyGroups.ElementAt(facCounter).Value;

                Word.Table oTable;
                Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                oTable = oDoc.Tables.Add(wrdRng, 1 + facultyExams.Keys.Count, 1 + groups.Count);

                //oTable.Rows(1).HeadingFormat = True;
                //oTable.ApplyStyleHeadingRows = True;
                oTable.Rows[1].HeadingFormat = -1;
                oTable.ApplyStyleHeadingRows = true;

                oTable.Borders.Enable = 1;

                for (int i = 1; i <= oTable.Rows.Count; i++)
                {
                    oTable.Rows[i].AllowBreakAcrossPages = (int)Microsoft.Office.Core.MsoTriState.msoFalse;
                }

                oTable.Cell(1, 1).Range.Text = "Дата";
                oTable.Cell(1, 1).Range.ParagraphFormat.Alignment =
                        Word.WdParagraphAlignment.wdAlignParagraphCenter;
                for (var column = 1; column <= groups.Count; column++)
                {
                    oTable.Cell(1, column + 1).Range.Text = groups[column - 1];
                    oTable.Cell(1, column + 1).Range.ParagraphFormat.Alignment =
                        Word.WdParagraphAlignment.wdAlignParagraphCenter;
                }

                for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++)
                {
                    oTable.Cell(row, 1).Range.Text = facultyExams.Keys.ElementAt(row - 2).ToString("dd MMMM yyyy", CultureInfo.CreateSpecificCulture("ru-RU"));
                    oTable.Cell(row, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                    oTable.Cell(row, 1).Range.ParagraphFormat.Alignment =
                        Word.WdParagraphAlignment.wdAlignParagraphCenter;
                }

                DateTime currentDate;

                for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++)
                {
                    currentDate = facultyExams.Keys.ElementAt(row - 2);

                    for (var column = 1; column <= groups.Count; column++)
                    {
                        if (facultyExams.ContainsKey(currentDate))
                        {
                            if (facultyExams[currentDate].ContainsKey(groupIds[column - 1]))
                            {
                                var eventCount = facultyExams[currentDate][groupIds[column - 1]].Count;

                                oTable.Cell(row, column + 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                                var timeTable = oDoc.Tables.Add(oTable.Cell(row, column + 1).Range, 1, 1);
                                timeTable.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitWindow);
                                if (eventCount > 1)
                                {
                                    for (int i = 1; i < eventCount; i++)
                                    {
                                        timeTable.Rows.Add();
                                    }
                                }

                                for (int i = 0; i < eventCount; i++)
                                {
                                    string cellText = "";

                                    var evt = facultyExams[currentDate][groupIds[column - 1]][i];

                                    // Консультация || Экзамен
                                    if (evt.IsExam)
                                    {
                                        cellText += "Экзамен";
                                    }
                                    else
                                    {
                                        cellText += "Консультация";
                                    }

                                    cellText += Environment.NewLine;
                                    cellText += evt.DisciplineName + Environment.NewLine;
                                    cellText += evt.TeacherFIO + Environment.NewLine;
                                    cellText += evt.Time.ToString("H:mm") + Environment.NewLine;
                                    cellText += evt.Auditorium;

                                    oPara1 = oDoc.Content.Paragraphs.Add(timeTable.Cell(i + 1, 1).Range);
                                    oPara1.Range.Font.Size = 10;
                                    oPara1.Format.SpaceAfter = 0;
                                    oPara1.Range.Text = cellText;

                                    if (i != eventCount - 1)
                                    {
                                        timeTable.Cell(i + 1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = true;
                                    }
                                }
                            }
                        }
                    }

                }

                oTable.Columns[1].Width = oWord.CentimetersToPoints(3);
                for (int i = 0; i < groups.Count; i++)
                {
                    oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(16 / groups.Count);
                }

                oTable.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter;

                Word.Paragraph oPara2 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara2.Range.Font.Size = 12;
                oPara2.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara2.Range.Text = "";
                oPara2.Format.SpaceAfter = 0;
                oPara2.Range.InsertParagraphAfter();

                oPara2 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara2.Range.Font.Size = 12;
                oPara2.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara2.Range.Text = "Начальник учебного отдела\t\t" + "_________________  " + Constants.Constants.UchOtdHead;
                oPara2.Format.SpaceAfter = 0;
                oPara2.Range.InsertParagraphAfter();
                oPara2.Range.InsertParagraphAfter();

                oPara2 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara2.Range.Font.Size = 12;
                oPara2.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara2.Range.Text = "Декан " + Constants.Constants.facultyTitles[facCounter] + "\t\t_________________  "
                    + Constants.Constants.HeadsOfFaculties.ElementAt(facCounter).Value;
                oPara2.Format.SpaceAfter = 0;
                oPara2.Range.InsertParagraphAfter();
                oPara2.Range.InsertParagraphAfter();

                if (facCounter != Constants.Constants.facultyGroups.Keys.Count - 1)
                {
                    oDoc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak);
                }

                Application.DoEvents();

            }

            object fileName = Application.StartupPath + @"\Export2.docx";

            //oDoc.SaveAs(ref fileName);

            //oWord.Quit();
        }
コード例 #3
0
        /// <summary>
        /// 修改文本样式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextFormat_Click(object sender, RibbonControlEventArgs e)
        {
            //弹出窗体提示
            DialogResult IsWait = MessageBox.Show("如果文本行较多运行较为缓慢,进度可在Word左下角查看" + Environment.NewLine + "是否继续?", "请选择", MessageBoxButtons.YesNo);

            if (IsWait != DialogResult.Yes)
            {
                return;
            }

            WordApp = Globals.ThisAddIn.Application;
            WordDoc = WordApp.ActiveDocument;


            WordApp.ScreenUpdating = false;//关闭屏幕刷新

            //读取配置文件
            ClsThisAddinConfig clsConfig = new ClsThisAddinConfig(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments));

            //正文字体字号
            bool    FontGroupCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "FontGroupCheck", true);
            string  CnFont         = clsConfig.ReadConfig <string>("SettingFormatForm", "CnFont", "仿宋_GB2312");
            string  NumFont        = clsConfig.ReadConfig <string>("SettingFormatForm", "NumFont", "Arial Narrow");
            decimal FontSize       = FormatFunC.FontSize(clsConfig.ReadConfig <string>("SettingFormatForm", "FontSize", "小四"));

            //标题行间距
            bool    TitleGroupCheck  = clsConfig.ReadConfig <bool>("SettingFormatForm", "TitleGroupCheck", true);
            bool    TitleIndentCkeck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TitleIndentCkeck", true);
            bool    FirstTitleCheck  = clsConfig.ReadConfig <bool>("SettingFormatForm", "FirstTitleCheck", true);
            decimal BeforeMainBody   = clsConfig.ReadConfig <decimal>("SettingFormatForm", "BeforeMainBody", 0m);
            decimal AfterMainBody    = clsConfig.ReadConfig <decimal>("SettingFormatForm", "AfterMainBody", 0.9m);
            decimal RowSpace         = FormatFunC.RowSpace(clsConfig.ReadConfig <string>("SettingFormatForm", "RowSpace", "单倍行距"));
            //跳过的段落数
            int SkipPgNum = FunC.TI(clsConfig.ReadConfig <decimal>("SettingFormatForm", "SkipPgs", 0m));

            //段落大纲级别
            Word.WdOutlineLevel PgLevel;


            if (FontGroupCheck || TitleGroupCheck)
            {
                //在状态栏显示进度
                WordApp.StatusBar = "当前进度:0%";

                int i3 = WordDoc.Paragraphs.Count;

                if (FontGroupCheck)
                {
                    WordApp.Selection.WholeStory();
                    WordApp.Selection.Font.Name = CnFont;
                    WordApp.Selection.Font.Name = NumFont;
                }

                int i4 = 0;
                foreach (Word.Paragraph Pg in WordDoc.Paragraphs)
                {
                    i4++;
                    if (i4 <= SkipPgNum)
                    {
                        continue;
                    }
                    if (Pg.Range.Information[Word.WdInformation.wdWithInTable])
                    {
                        continue;
                    }
                    PgLevel = Pg.OutlineLevel;

                    //如果勾选了标题段落,调整段前段后行间距
                    if (TitleGroupCheck)
                    {
                        //段前间距
                        Pg.SpaceBefore    = 0;
                        Pg.LineUnitBefore = float.Parse(BeforeMainBody.ToString());
                        //段后间距
                        Pg.SpaceAfter    = 0;
                        Pg.LineUnitAfter = float.Parse(AfterMainBody.ToString());
                        //段落行间距
                        Pg.LineSpacing = WordApp.LinesToPoints(float.Parse(RowSpace.ToString()));
                    }

                    if (PgLevel == Word.WdOutlineLevel.wdOutlineLevelBodyText)
                    {
                        if (FontGroupCheck)
                        {
                            Pg.Range.Font.Size = float.Parse(FontSize.ToString());
                        }
                    }
                    else
                    {
                        if (TitleGroupCheck)
                        {
                            if (TitleIndentCkeck)
                            {
                                Pg.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                                Pg.CharacterUnitLeftIndent = -2;
                            }

                            if (FirstTitleCheck)
                            {
                                if (PgLevel == Word.WdOutlineLevel.wdOutlineLevel1)
                                {
                                    Pg.SpaceBefore    = 0;
                                    Pg.LineUnitBefore = 0.5f;
                                }
                            }
                        }
                    }

                    //调整表格下一行间距
                    if (TitleGroupCheck && FirstTitleCheck && i4 > 1)
                    {
                        if (WordDoc.Paragraphs[i4 - 1].Range.Information[Word.WdInformation.wdWithInTable])
                        {
                            Pg.SpaceBefore    = 0;
                            Pg.LineUnitBefore = 0.5f;
                        }
                    }

                    //显示进度
                    WordApp.StatusBar = "当前进度:" + Math.Round((i4 * 100d / i3), 2) + "%";
                }
            }

            WordApp.ScreenUpdating = true;//关闭屏幕刷新
        }
コード例 #4
0
        /// <summary>
        /// 修改表格样式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TableFormat_Click(object sender, RibbonControlEventArgs e)
        {
            //弹出窗体提示
            DialogResult IsWait = MessageBox.Show("如果表格较多运行较为缓慢,进度可在Word左下角查看" + Environment.NewLine + "是否继续?", "请选择", MessageBoxButtons.YesNo);

            if (IsWait != DialogResult.Yes)
            {
                return;
            }

            WordApp = Globals.ThisAddIn.Application;
            WordDoc = WordApp.ActiveDocument;

            WordApp.ScreenUpdating = false; //关闭屏幕刷新

            #region                         //读取配置文件
            //读取配置文件
            ClsThisAddinConfig clsConfig = new ClsThisAddinConfig(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments));

            //表格间距
            bool SpaceGroupCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "SpaceGroupCheck", true);
            //首行缩进
            bool TableIndentCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableIndentCheck", true);
            //段前
            decimal TableBeforeMainBody = clsConfig.ReadConfig <decimal>("SettingFormatForm", "TableBeforeMainBody", 0m);
            //段后
            decimal TableAfterMainBody = clsConfig.ReadConfig <decimal>("SettingFormatForm", "TableAfterMainBody", 0m);
            //行间距
            decimal TableRowSpace = FormatFunC.RowSpace(clsConfig.ReadConfig <string>("SettingFormatForm", "TableRowSpace", "单倍行距"));

            //表格边框
            bool BorderGroupCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "BorderGroupCheck", true);
            //上下边框宽度1磅
            bool TableTBBorderCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableTBBorderCheck", true);
            //左右无边框
            bool TableLRBorderCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableLRBorderCheck", true);

            //表格其他选项
            bool OtherGroupCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "OtherGroupCheck", true);
            //垂直居中
            bool TableVerticalCenterCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableVerticalCenterCheck", true);
            //标题及合计行加粗
            bool TableTitleWiderCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableTitleWiderCheck", true);
            //表格字号
            decimal TableFontSize = FormatFunC.FontSize(clsConfig.ReadConfig <string>("SettingFormatForm", "TableFontSize", "小四"));
            #endregion

            if (SpaceGroupCheck || BorderGroupCheck || OtherGroupCheck)
            {
                //在状态栏显示进度
                WordApp.StatusBar = "当前进度:0%";
                int i3 = WordDoc.Tables.Count;

                int i4 = 1;
                foreach (Word.Table Tb in WordDoc.Tables)
                {
                    Tb.Select();

                    //间距
                    if (SpaceGroupCheck)
                    {
                        if (TableIndentCheck)
                        {
                            WordApp.Selection.ParagraphFormat.CharacterUnitLeftIndent      = 0;
                            WordApp.Selection.ParagraphFormat.CharacterUnitRightIndent     = 0;
                            WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = 0;
                            WordApp.Selection.ParagraphFormat.FirstLineIndent = WordApp.CentimetersToPoints(0);
                        }
                        WordApp.Selection.ParagraphFormat.SpaceBefore           = 0;
                        WordApp.Selection.ParagraphFormat.LineUnitBefore        = float.Parse(TableBeforeMainBody.ToString());
                        WordApp.Selection.ParagraphFormat.SpaceAfter            = 0;
                        WordApp.Selection.ParagraphFormat.LineUnitAfter         = float.Parse(TableAfterMainBody.ToString());
                        WordApp.Selection.ParagraphFormat.LineSpacing           = WordApp.LinesToPoints(float.Parse(TableRowSpace.ToString()));
                        WordApp.Selection.ParagraphFormat.DisableLineHeightGrid = -1; //行距设置中,不勾选“如果定义了文档网格,则于网格对齐”
                        WordApp.Selection.ParagraphFormat.AutoAdjustRightIndent = -1; //行距设置中,不勾选“如果定义了文档网格,则自动调整右缩进”
                    }

                    //边框
                    if (BorderGroupCheck)
                    {
                        //上下边框1磅
                        if (TableTBBorderCheck)
                        {
                            Tb.Borders[Word.WdBorderType.wdBorderTop].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                            Tb.Borders[Word.WdBorderType.wdBorderTop].LineWidth = Word.WdLineWidth.wdLineWidth100pt;
                            Tb.Borders[Word.WdBorderType.wdBorderTop].Color     = Word.WdColor.wdColorAutomatic;

                            Tb.Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                            Tb.Borders[Word.WdBorderType.wdBorderBottom].LineWidth = Word.WdLineWidth.wdLineWidth100pt;
                            Tb.Borders[Word.WdBorderType.wdBorderBottom].Color     = Word.WdColor.wdColorAutomatic;
                        }
                        //左右无边框
                        if (TableLRBorderCheck)
                        {
                            Tb.Borders[Word.WdBorderType.wdBorderLeft].LineStyle  = Word.WdLineStyle.wdLineStyleNone;
                            Tb.Borders[Word.WdBorderType.wdBorderRight].LineStyle = Word.WdLineStyle.wdLineStyleNone;
                        }
                    }

                    //其他选项
                    if (OtherGroupCheck)
                    {
                        //垂直居中
                        if (TableVerticalCenterCheck)
                        {
                            WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        }
                        //
                        if (TableTitleWiderCheck)
                        {
                        }
                        //表格字体
                        Tb.Range.Font.Size = float.Parse(TableFontSize.ToString());
                    }


                    //显示进度
                    WordApp.StatusBar = "当前进度:" + Math.Round((i4 * 100d / i3), 2) + "%";
                    i4++;
                }
            }

            WordApp.ScreenUpdating = true;//关闭屏幕刷新
        }
コード例 #5
0
ファイル: WordExport.cs プロジェクト: BesuglovS/UchOtd
        public static void ExportSchedulePage(ScheduleRepository repo, string filename, bool save, bool quit,
            int lessonLength, int facultyId, int dayOfWeek, int daysOfWeek, bool weekFiltered, int weekFilter,
            bool weeksMarksVisible, bool onlyFutureDates, CancellationToken cToken)
        {
            object oMissing = Missing.Value;
            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

            cToken.ThrowIfCancellationRequested();

            //Start Word and create a new document.
            _Application oWord = new Application { Visible = true };
            _Document oDoc = oWord.Documents.Add();

            oDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
            oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1);
            oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1);
            oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1);
            oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1);

            var faculty = repo.Faculties.GetFaculty(facultyId);

            var dow = Constants.DowLocal[dayOfWeek];

            var schedule = repo.Lessons.GetFacultyDowSchedule(faculty.FacultyId, dayOfWeek, weekFiltered, weekFilter, false, onlyFutureDates);

            Paragraph oPara1 = oDoc.Content.Paragraphs.Add();
            oPara1.Range.Text = "Расписание";
            oPara1.Range.Font.Bold = 0;
            oPara1.Range.Font.Size = 10;
            oPara1.Range.ParagraphFormat.LineSpacingRule =
                WdLineSpacing.wdLineSpaceSingle;
            oPara1.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            oPara1.SpaceAfter = 0;
            oPara1.Range.InsertParagraphAfter();

            var textBoxRange = oPara1.Range;

            oPara1 = oDoc.Content.Paragraphs.Add();
            //oPara1.Range.Text = "второго семестра 2013 – 2014 учебного года";
            oPara1.Range.Text = DetectSemesterString(repo);
            oPara1.Range.Font.Bold = 0;
            oPara1.Range.Font.Size = 10;
            oPara1.Range.ParagraphFormat.LineSpacingRule =
                WdLineSpacing.wdLineSpaceSingle;
            oPara1.Range.InsertParagraphAfter();

            oPara1 = oDoc.Content.Paragraphs.Add();
            oPara1.Range.Text = faculty.Name;
            oPara1.Range.Font.Bold = 0;
            oPara1.Range.Font.Size = 10;
            oPara1.Range.ParagraphFormat.LineSpacingRule =
                WdLineSpacing.wdLineSpaceSingle;
            oPara1.Range.InsertParagraphAfter();

            oPara1 = oDoc.Content.Paragraphs.Add();
            oPara1.Range.Font.Size = 14;
            oPara1.Range.Text = dow.ToUpper();
            oPara1.Range.Font.Bold = 1;
            oPara1.Range.ParagraphFormat.LineSpacingRule =
                WdLineSpacing.wdLineSpaceSingle;
            oPara1.Range.InsertParagraphAfter();

            Shape cornerStamp = oDoc.Shapes.AddTextbox(
                MsoTextOrientation.msoTextOrientationHorizontal,
                oWord.CentimetersToPoints(22f),
                oWord.CentimetersToPoints(0.5f),
                200, 50,
                textBoxRange);
            cornerStamp.TextFrame.TextRange.ParagraphFormat.LineSpacingRule =
                WdLineSpacing.wdLineSpaceSingle;
            if (dow == "Понедельник")
            {
                var prorUchRabNameOption = repo.ConfigOptions.GetFirstFiltredConfigOption(co => co.Key == "Проректор по учебной работе");
                var prorUchRabName = (prorUchRabNameOption == null) ? "" : prorUchRabNameOption.Value;

                cornerStamp.TextFrame.TextRange.Text = @"«УТВЕРЖДАЮ»" +
                    Environment.NewLine + "Проректор по учебной работе" +
                    Environment.NewLine + "______________     " + prorUchRabName;
                cornerStamp.TextFrame.TextRange.Font.Size = 10;
                cornerStamp.TextFrame.TextRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
            }
            cornerStamp.TextFrame.WordWrap = 1;
            cornerStamp.TextFrame.TextRange.ParagraphFormat.SpaceAfter = 0;
            cornerStamp.Line.Visible = MsoTriState.msoFalse;

            var timeList = new List<string>();
            foreach (var group in schedule)
            {
                foreach (var time in group.Value.Keys)
                {
                    if (!timeList.Contains(time))
                    {
                        timeList.Add(time);
                    }
                }
            }

            Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            cToken.ThrowIfCancellationRequested();

            Table oTable = oDoc.Tables.Add(wrdRng, 1 + timeList.Count, 1 + schedule.Count);
            oTable.Borders.Enable = 1;
            oTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
            oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
            oTable.Range.Font.Size = 10;
            oTable.Range.Font.Bold = 0;

            oTable.Columns[1].Width = oWord.CentimetersToPoints(2.44f);
            float colWidth = 25.64F / schedule.Count;
            for (int i = 0; i < schedule.Count; i++)
            {
                oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(colWidth);
            }

            oTable.Cell(1, 1).Range.Text = "Время";
            oTable.Cell(1, 1).Range.ParagraphFormat.Alignment =
                        WdParagraphAlignment.wdAlignParagraphCenter;

            int groupColumn = 2;

            var plainGroupsListIds = new Dictionary<int, List<int>>();
            var nGroupsListIds = new Dictionary<int, List<int>>();
            var plainNGroupIds = new Dictionary<int, Tuple<int, int>>();

            foreach (var group in schedule)
            {
                var groupObject = repo.StudentGroups.GetStudentGroup(group.Key);
                var groupName = groupObject.Name;
                oTable.Cell(1, groupColumn).Range.Text = groupName.Replace(" (+Н)", "");
                oTable.Cell(1, groupColumn).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                groupColumn++;

                if (groupName.Contains(" (+Н)"))
                {
                    var plainGroupName = groupName.Replace(" (+Н)", "");
                    var nGroupName = groupName.Replace(" (+", "(");

                    var plainGroupId = repo.StudentGroups.FindStudentGroup(plainGroupName).StudentGroupId;
                    var plainStudentIds = repo.StudentsInGroups.GetAllStudentsInGroups()
                            .Where(sig => sig.StudentGroup.StudentGroupId == plainGroupId)
                            .Select(stig => stig.Student.StudentId)
                            .ToList();
                    plainGroupsListIds.Add(group.Key, repo.StudentsInGroups.GetAllStudentsInGroups()
                            .Where(sig => plainStudentIds.Contains(sig.Student.StudentId))
                            .Select(stig => stig.StudentGroup.StudentGroupId)
                            .Distinct()
                            .ToList());

                    var nGroupId = repo.StudentGroups.FindStudentGroup(nGroupName).StudentGroupId;
                    var nStudentIds = repo.StudentsInGroups.GetAllStudentsInGroups()
                            .Where(sig => sig.StudentGroup.StudentGroupId == nGroupId)
                            .Select(stig => stig.Student.StudentId)
                            .ToList();
                    nGroupsListIds.Add(group.Key, repo.StudentsInGroups.GetAllStudentsInGroups()
                            .Where(sig => nStudentIds.Contains(sig.Student.StudentId))
                            .Select(stig => stig.StudentGroup.StudentGroupId)
                            .Distinct()
                            .ToList());

                    plainNGroupIds.Add(groupObject.StudentGroupId, new Tuple<int, int>(plainGroupId, nGroupId));
                }
            }

            cToken.ThrowIfCancellationRequested();

            var timeRowIndexList = new List<int>();

            var timeRowIndex = 2;
            foreach (var time in timeList.OrderBy(t => int.Parse(t.Split(':')[0]) * 60 + int.Parse(t.Split(':')[1])))
            {
                cToken.ThrowIfCancellationRequested();

                var hour = int.Parse(time.Substring(0, 2));
                var minute = int.Parse(time.Substring(3, 2));

                minute += lessonLength;

                while (minute >= 60)
                {
                    hour++;
                    minute -= 60;
                }

                timeRowIndexList.Add(timeRowIndex);
                oTable.Cell(timeRowIndex, 1).Range.Text = time + " - " +
                    hour.ToString("D2") + ":" + minute.ToString("D2");
                oTable.Cell(timeRowIndex, 1).Range.ParagraphFormat.Alignment =
                        WdParagraphAlignment.wdAlignParagraphCenter;
                oTable.Cell(timeRowIndex, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                var columnGroupIndex = 2;
                foreach (var group in schedule)
                {
                    if (group.Value.ContainsKey(time))
                    {
                        oTable.Cell(timeRowIndex, columnGroupIndex).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                        var timeTable = oDoc.Tables.Add(oTable.Cell(timeRowIndex, columnGroupIndex).Range, 1, 1);
                        for (int i = 0; i < group.Value[time].Count - 1; i++)
                        {
                            timeTable.Rows.Add();
                        }
                        for (int i = 0; i < group.Value[time].Count - 1; i++)
                        {
                            timeTable.Cell(i + 1, 1).Borders[WdBorderType.wdBorderBottom].Visible = true;
                        }
                        timeTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
                        timeTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                        timeTable.Range.Font.Size = 10;
                        timeTable.Range.Font.Bold = 0;

                        var tfdIndex = 0;
                        foreach (var tfdData in group.Value[time].OrderBy(tfd => tfd.Value.Item2.Select(lwt => repo.CommonFunctions.CalculateWeekNumber(lwt.Item1.Calendar.Date)).Min()))
                        {
                            var cellText = "";

                            // Discipline name
                            var primaryDisciplineName = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.Name;
                            var names =
                                repo.DisciplineNames.GetDisciplineNamesDictionary(
                                    tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline);

                            if (names.ContainsKey(group.Key))
                            {
                                cellText += names[group.Key];
                            }
                            else
                            {
                                cellText += primaryDisciplineName;
                            }

                            // N + Group modifiers
                            var groupId = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId;
                            if (plainGroupsListIds.ContainsKey(group.Key))
                            {
                                if (plainGroupsListIds[group.Key].Contains(groupId) && nGroupsListIds[group.Key].Contains(groupId))
                                {
                                    cellText += " (+Н)";
                                }
                                if (!plainGroupsListIds[group.Key].Contains(groupId) && nGroupsListIds[group.Key].Contains(groupId))
                                {
                                    cellText += " (Н)";
                                }
                            }

                            var tfdGroupId = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId;
                            if ((tfdGroupId != group.Key))
                            {
                                if ((!plainNGroupIds.ContainsKey(group.Key)) || ((tfdGroupId != plainNGroupIds[group.Key].Item1) && (tfdGroupId != plainNGroupIds[group.Key].Item2)))
                                {
                                    cellText += " (" + tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.Name + ")";
                                }
                            }

                            cellText += Environment.NewLine;
                            // Teacher FIO
                            cellText += tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Teacher.FIO + Environment.NewLine;

                            // Total weeks
                            if (weeksMarksVisible)
                            {
                                cellText += "(" + tfdData.Value.Item1 + ")" + Environment.NewLine;
                            }

                            var audWeekList = tfdData.Value.Item2.ToDictionary(l => repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date), l => l.Item1.Auditorium.Name);
                            var grouped = audWeekList.GroupBy(a => a.Value);

                            var enumerable = grouped as List<IGrouping<string, KeyValuePair<int, string>>> ?? grouped.ToList();
                            var gcount = enumerable.Count();
                            if (gcount == 1)
                            {
                                cellText += enumerable.ElementAt(0).Key;
                            }
                            else
                            {
                                for (int j = 0; j < gcount; j++)
                                {
                                    var jItem = enumerable.OrderBy(e => e.Select(ag => ag.Key).ToList().Min()).ElementAt(j);
                                    cellText += CommonFunctions.CombineWeeks(jItem.Select(ag => ag.Key).ToList()) + " - " + jItem.Key;

                                    if (j != gcount - 1)
                                    {
                                        cellText += Environment.NewLine;
                                    }
                                }
                            }

                            timeTable.Cell(tfdIndex + 1, 1).Range.Text = cellText;
                            timeTable.Cell(tfdIndex + 1, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                            tfdIndex++;

                        }
                    }

                    columnGroupIndex++;
                }

                timeRowIndex++;
            }

            if (dayOfWeek == daysOfWeek)
            {
                var oPara3 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara3.Range.Font.Size = 12;
                oPara3.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara3.Range.Text = "";
                oPara3.Format.SpaceAfter = 0;
                oPara3.Range.InsertParagraphAfter();

                var headUchOtdNameOption = repo.ConfigOptions.GetFirstFiltredConfigOption(co => co.Key == "Начальник учебного отдела");
                var headUchOtdName = (headUchOtdNameOption == null) ? "" : headUchOtdNameOption.Value;

                oPara3 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara3.Range.Text = "Начальник учебного отдела\t\t" + "_________________  " + headUchOtdName;
                oPara3.Range.Font.Size = 12;
                oPara3.Range.Font.Bold = 0;
                oPara3.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                oPara3.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara3.Format.SpaceAfter = 0;
                oPara3.Range.InsertParagraphAfter();
                oPara3.Range.InsertParagraphAfter();

                oPara3 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                //"Декан " + UchOtd.NUDS.Core.Constants.facultyTitles[facCounter] + "\t\t_________________  "
                //+ UchOtd.NUDS.Core.Constants.HeadsOfFaculties.ElementAt(facCounter).Value;
                oPara3.Range.Text = faculty.ScheduleSigningTitle + "\t\t_________________  " + faculty.DeanSigningSchedule;
                oPara3.Range.Font.Size = 12;
                oPara3.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                oPara3.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara3.Range.Font.Bold = 0;
                oPara3.Format.SpaceAfter = 0;
            }

            cToken.ThrowIfCancellationRequested();

            int pageCount;
            var fontSize = 10.5F;
            do
            {
                fontSize -= 0.5F;
                oTable.Range.Font.Size = fontSize;

                if (fontSize <= 3)
                {
                    break;
                }

                pageCount = oDoc.ComputeStatistics(WdStatistic.wdStatisticPages);
            } while (pageCount > 1);

            if (save)
            {
                object fileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + filename;
                oDoc.SaveAs(ref fileName);
            }

            if (quit)
            {
                oWord.Quit();
            }

            Marshal.ReleaseComObject(oWord);
        }
コード例 #6
0
ファイル: MainForm.cs プロジェクト: BesuglovS/Session
        private void SaveAsWordDocument()
        {
            DateTime beginSessionDate, endSessionDate;

            DetectSessionDates(out beginSessionDate, out endSessionDate);


            object oMissing  = System.Reflection.Missing.Value;
            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

            //Start Word and create a new document.

            Word._Application oWord = new Word.Application();
            oWord.Visible = true;
            Word._Document oDoc =
                oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            oDoc.PageSetup.TopMargin    = oWord.CentimetersToPoints(1);
            oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1);
            oDoc.PageSetup.LeftMargin   = oWord.CentimetersToPoints(1);
            oDoc.PageSetup.RightMargin  = oWord.CentimetersToPoints(1);

            var faculties = _sRepo.GetAllFaculties();

            for (int facCounter = 0; facCounter < Constants.Constants.facultyGroups.Keys.Count; facCounter++)
            {
                var groupIds = new List <int>();

                foreach (var group in Constants.Constants.facultyGroups.ElementAt(facCounter).Value)
                {
                    var groupId = _sRepo.FindStudentGroup(group);
                    if (groupId != null)
                    {
                        groupIds.Add(groupId.StudentGroupId);
                    }
                }

                var facultyExams = _repo.GetFacultyExams(_sRepo, groupIds);

                facultyExams = facultyExams.OrderBy(fe => fe.Key).ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);

                Word.Paragraph oPara1 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara1.Range.Font.Size    = 24;
                oPara1.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara1.Range.Text         = "Расписание";
                oPara1.Format.SpaceAfter  = 0;
                oPara1.Range.InsertParagraphAfter();

                oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara1.Range.Font.Size   = 14;
                oPara1.Format.SpaceAfter = 0;
                if (beginSessionDate.Month < 3)
                {
                    var startYear = beginSessionDate.Year - 1;
                    oPara1.Range.Text = "зимней сессии " + startYear + "-" + (startYear + 1) + " учебного года" +
                                        Environment.NewLine + Constants.Constants.facultyTitles[facCounter];
                }
                else
                {
                    var startYear = beginSessionDate.Year - 1;
                    oPara1.Range.Text = "летней сессии " + startYear + "-" + (startYear + 1) + " учебного года" +
                                        Environment.NewLine + Constants.Constants.facultyTitles[facCounter];
                }
                oPara1.Range.InsertParagraphAfter();

                Word.Shape signBox = oDoc.Shapes
                                     .AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 350, 15, 200, 75, oPara1.Range);

                signBox.Line.Visible = MsoTriState.msoFalse;
                signBox.TextFrame.ContainingRange.ParagraphFormat.Alignment =
                    Word.WdParagraphAlignment.wdAlignParagraphRight;

                signBox.TextFrame.ContainingRange.InsertAfter("«УТВЕРЖДАЮ»");
                signBox.TextFrame.ContainingRange.InsertParagraphAfter();
                signBox.TextFrame.ContainingRange.InsertAfter("Проректор по учебной работе");
                signBox.TextFrame.ContainingRange.InsertParagraphAfter();
                signBox.TextFrame.ContainingRange.InsertAfter("____________  А.В. Синицкий");

                var groups = Constants.Constants.facultyGroups.ElementAt(facCounter).Value;

                Word.Table oTable;
                Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                oTable = oDoc.Tables.Add(wrdRng, 1 + facultyExams.Keys.Count, 1 + groups.Count);

                //oTable.Rows(1).HeadingFormat = True;
                //oTable.ApplyStyleHeadingRows = True;
                oTable.Rows[1].HeadingFormat = -1;
                oTable.ApplyStyleHeadingRows = true;

                oTable.Borders.Enable = 1;

                for (int i = 1; i <= oTable.Rows.Count; i++)
                {
                    oTable.Rows[i].AllowBreakAcrossPages = (int)Microsoft.Office.Core.MsoTriState.msoFalse;
                }


                oTable.Cell(1, 1).Range.Text = "Дата";
                oTable.Cell(1, 1).Range.ParagraphFormat.Alignment =
                    Word.WdParagraphAlignment.wdAlignParagraphCenter;
                for (var column = 1; column <= groups.Count; column++)
                {
                    oTable.Cell(1, column + 1).Range.Text = groups[column - 1];
                    oTable.Cell(1, column + 1).Range.ParagraphFormat.Alignment =
                        Word.WdParagraphAlignment.wdAlignParagraphCenter;
                }

                for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++)
                {
                    oTable.Cell(row, 1).Range.Text        = facultyExams.Keys.ElementAt(row - 2).ToString("dd MMMM yyyy", CultureInfo.CreateSpecificCulture("ru-RU"));
                    oTable.Cell(row, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                    oTable.Cell(row, 1).Range.ParagraphFormat.Alignment =
                        Word.WdParagraphAlignment.wdAlignParagraphCenter;
                }

                DateTime currentDate;

                for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++)
                {
                    currentDate = facultyExams.Keys.ElementAt(row - 2);

                    for (var column = 1; column <= groups.Count; column++)
                    {
                        if (facultyExams.ContainsKey(currentDate))
                        {
                            if (facultyExams[currentDate].ContainsKey(groupIds[column - 1]))
                            {
                                var eventCount = facultyExams[currentDate][groupIds[column - 1]].Count;

                                oTable.Cell(row, column + 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                                var timeTable = oDoc.Tables.Add(oTable.Cell(row, column + 1).Range, 1, 1);
                                timeTable.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitWindow);
                                if (eventCount > 1)
                                {
                                    for (int i = 1; i < eventCount; i++)
                                    {
                                        timeTable.Rows.Add();
                                    }
                                }

                                for (int i = 0; i < eventCount; i++)
                                {
                                    string cellText = "";

                                    var evt = facultyExams[currentDate][groupIds[column - 1]][i];

                                    // Консультация || Экзамен
                                    if (evt.IsExam)
                                    {
                                        cellText += "Экзамен";
                                    }
                                    else
                                    {
                                        cellText += "Консультация";
                                    }

                                    cellText += Environment.NewLine;
                                    cellText += evt.DisciplineName + Environment.NewLine;
                                    cellText += evt.TeacherFIO + Environment.NewLine;
                                    cellText += evt.Time.ToString("H:mm") + Environment.NewLine;
                                    cellText += evt.Auditorium;

                                    oPara1 = oDoc.Content.Paragraphs.Add(timeTable.Cell(i + 1, 1).Range);
                                    oPara1.Range.Font.Size   = 10;
                                    oPara1.Format.SpaceAfter = 0;
                                    oPara1.Range.Text        = cellText;

                                    if (i != eventCount - 1)
                                    {
                                        timeTable.Cell(i + 1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = true;
                                    }
                                }
                            }
                        }
                    }
                }


                oTable.Columns[1].Width = oWord.CentimetersToPoints(3);
                for (int i = 0; i < groups.Count; i++)
                {
                    oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(16 / groups.Count);
                }

                oTable.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter;

                Word.Paragraph oPara2 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara2.Range.Font.Size    = 12;
                oPara2.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara2.Range.Text         = "";
                oPara2.Format.SpaceAfter  = 0;
                oPara2.Range.InsertParagraphAfter();

                oPara2 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara2.Range.Font.Size    = 12;
                oPara2.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara2.Range.Text         = "Начальник учебного отдела\t\t" + "_________________  " + Constants.Constants.UchOtdHead;
                oPara2.Format.SpaceAfter  = 0;
                oPara2.Range.InsertParagraphAfter();
                oPara2.Range.InsertParagraphAfter();

                oPara2 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara2.Range.Font.Size    = 12;
                oPara2.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara2.Range.Text         = "Декан " + Constants.Constants.facultyTitles[facCounter] + "\t\t_________________  "
                                            + Constants.Constants.HeadsOfFaculties.ElementAt(facCounter).Value;
                oPara2.Format.SpaceAfter = 0;
                oPara2.Range.InsertParagraphAfter();
                oPara2.Range.InsertParagraphAfter();


                if (facCounter != Constants.Constants.facultyGroups.Keys.Count - 1)
                {
                    oDoc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak);
                }

                Application.DoEvents();
            }

            object fileName = Application.StartupPath + @"\Export2.docx";

            //oDoc.SaveAs(ref fileName);

            //oWord.Quit();
        }
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Word.Application wa     = null;
            Word.Document    doc    = main.CreateNewWordDoc(ref wa);
            object           nulval = Type.Missing;

            string prname = KursRabotaList.Rows[kursRablistBox.SelectedIndex][2].ToString();

            Word.Range Range = doc.Range(ref nulval, ref nulval);
            Range.Select();
            Range.ParagraphFormat.FirstLineIndent = 0.0f;

            Range = doc.Paragraphs[1].Range;
            Range.Select();
            Range.Text = "А К Т";
            Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            Range.Font.Bold   = 1;
            Range.Font.Italic = 1;

            Range = main.AddWordDocParagraph(ref doc,
                                             "сдачи курсовых работ  в архив", Word.WdParagraphAlignment.wdAlignParagraphCenter);
            Range.Font.Bold   = 0;
            Range.Font.Italic = 0;

            Range = main.AddWordDocParagraph(ref doc,
                                             " ", Word.WdParagraphAlignment.wdAlignParagraphCenter);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Комиссия в составе:  архивариус Зуенок Е.В.",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "\t\t\t" +
                                             " зам. декана ФИВТ     В.В. Семикина",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "\t\t\t" +
                                             " зав. кафедры КТИС   И.К. Мазур",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);


            Range = main.AddWordDocParagraph(ref doc,
                                             "FSystem ИВТ, кафедра  “Компьютерные технологии и системы”",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);


            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "За " + main.year_start.Year.ToString() + "/" + main.year_end.Year.ToString() + " уч. год",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);


            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Группа " + StudRabotaList.Rows[0][12].ToString().ToUpper(),
                                             Word.WdParagraphAlignment.wdAlignParagraphCenter);
            Range.Font.Bold = 1;

            Range = main.AddWordDocParagraph(ref doc,
                                             "Дисциплина “" + prname + "”",
                                             Word.WdParagraphAlignment.wdAlignParagraphCenter);
            Range.Font.Bold = 1;

            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);
            Range.Font.Bold = 0;


            List <int> tabrows = new List <int>();

            foreach (DataGridViewCell c in RabListdataGridView.SelectedCells)
            {
                MessageBox.Show(c.Value.ToString());

                if (!tabrows.Contains(c.RowIndex))
                {
                    tabrows.Add(c.RowIndex);
                }
            }

            int k = 1;

            for (int i = 0; i < tabrows.Count; i++)
            {
                int ind = tabrows[i];
                if (RabListdataGridView.Rows[ind].Cells[2].Value.ToString() != "2")
                {
                    if (RabListdataGridView.Rows[ind].Cells[1].Value.ToString().Length != 0)
                    {
                        Range = main.AddWordDocParagraph(ref doc,
                                                         k.ToString() + ". " + RabListdataGridView.Rows[ind].Cells[0].Value.ToString() +
                                                         " (" + RabListdataGridView.Rows[ind].Cells[1].Value.ToString() + ")",
                                                         Word.WdParagraphAlignment.wdAlignParagraphLeft);
                        k++;
                    }
                }
            }

            if (k == 1)
            {
                MessageBox.Show("Акт не построен. В таблице нет работ, " +
                                "которые могут быть актированы (либо у работ не указана тема,\nлибо все выбранные работы оценены на неудовлетворительно.",
                                "Отказ операции", MessageBoxButtons.OK, MessageBoxIcon.Error);
                main.WordQuit(wa);
                return;
            }

            saveExcel.Title    = "Введите имя для файла акта курсовой работы.";
            saveExcel.Filter   = "Файл акта КР в формате MS Word|*.doc";
            saveExcel.FileName = "Акт курс. работ по " + prname + ".doc";

            if (saveExcel.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string FileName = saveExcel.FileName;

            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Итого сдано работ: " + (k - 1).ToString(),
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);
            Range.Font.Bold      = 1;
            Range.Font.Underline = Word.WdUnderline.wdUnderlineSingle;

            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);
            Range.ParagraphFormat.LineSpacing = wa.LinesToPoints(1.5f);
            Range.Font.Bold      = 0;
            Range.Font.Underline = Word.WdUnderline.wdUnderlineNone;

            Range = main.AddWordDocParagraph(ref doc,
                                             "Преподаватель           " + main.active_user_name + "___________________",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Зав. кафедры КТИС   И.К. Мазур________________________",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Зам. декана ФИВТ     В.В. Семикина_____________________",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Архивариус           Зуенок Е.В._______________________",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Бухгалтер                   ________________________________",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             DateTime.Now.ToLongDateString(),
                                             Word.WdParagraphAlignment.wdAlignParagraphRight);

            main.SaveWordDoc(FileName, ref doc);
            wa.Visible = true;
            wa.Activate();
        }
コード例 #8
0
ファイル: Session.cs プロジェクト: BesuglovS/UchOtd
        private void SaveAsWordDocument(int facultyFilter)
        {
            DateTime beginSessionDate, endSessionDate;
            DetectSessionDates(out beginSessionDate, out endSessionDate);


            object oMissing = Missing.Value;
            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

            //Start Word and create a new document.

            _Application oWord = new Application();
            oWord.Visible = true;
            _Document oDoc =
                oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1);
            oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1);
            oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1);
            oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1);

            List<Faculty> faculties;

            if (facultyFilter != -1)
            {
                var onefaculty = _repo.Faculties.GetFaculty((int)FacultyList.SelectedValue);
                faculties = oneFaculty == null ? 
                    _repo.Faculties.GetAllFaculties().OrderBy(f => f.SortingOrder).ToList() : 
                    new List<Faculty> {onefaculty};
            }
            else
            {
                faculties = _repo.Faculties.GetAllFaculties().OrderBy(f => f.SortingOrder).ToList();
            }
            
            foreach (var faculty in faculties)
            {
                /*
                var groupIds = new List<int>();                
                foreach (var group in Constants.facultyGroups.ElementAt(facCounter).Value)
                {
                    var groupId = _repo.FindStudentGroup(group);
                    if (groupId != null)
                    {
                        groupIds.Add(groupId.StudentGroupId);
                    }
                }*/

                var localFaculty = faculty;
                var groupIds = _repo
                    .GroupsInFaculties
                    .GetFiltredGroupsInFaculty(gif => gif.Faculty.FacultyId == localFaculty.FacultyId)
                    .Select(gif => gif.StudentGroup.StudentGroupId)
                    .ToList();

                var facultyExams = _repo.Exams.GetFacultyExams(_repo, groupIds);

                facultyExams = facultyExams
                    .OrderBy(fe => fe.Key)
                    .ToDictionary(keyItem => keyItem.Key, valueItem => valueItem.Value);

                Paragraph oPara1 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara1.Range.Font.Size = 24;
                oPara1.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara1.Range.Text = "Расписание";
                oPara1.Format.SpaceAfter = 0;
                oPara1.Range.InsertParagraphAfter();

                oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara1.Range.Font.Size = 14;
                oPara1.Format.SpaceAfter = 0;
                if (beginSessionDate.Month < 3)
                {
                    var startYear = beginSessionDate.Year - 1;
                    oPara1.Range.Text = "зимней сессии " + startYear + "-" + (startYear + 1) + " учебного года" +
                        Environment.NewLine +
                        faculty.Name;
                }
                else
                {
                    var startYear = beginSessionDate.Year - 1;
                    oPara1.Range.Text = "летней сессии " + startYear + "-" + (startYear + 1) + " учебного года" +
                        Environment.NewLine +
                        faculty.Name;
                }
                oPara1.Range.InsertParagraphAfter();

                Shape signBox = oDoc.Shapes
                    .AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 350, 15, 200, 75, oPara1.Range);

                signBox.Line.Visible = MsoTriState.msoFalse;
                signBox.TextFrame.ContainingRange.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphRight;

                var prorUchRabNameOption = _repo.ConfigOptions.GetFirstFiltredConfigOption(co => co.Key == "Проректор по учебной работе");
                var prorUchRabName = (prorUchRabNameOption == null) ? "" : prorUchRabNameOption.Value;

                signBox.TextFrame.ContainingRange.InsertAfter("«УТВЕРЖДАЮ»");
                signBox.TextFrame.ContainingRange.InsertParagraphAfter();
                signBox.TextFrame.ContainingRange.InsertAfter("Проректор по учебной работе");
                signBox.TextFrame.ContainingRange.InsertParagraphAfter();
                signBox.TextFrame.ContainingRange.InsertAfter("____________  " + prorUchRabName);

                Faculty local2Faculty = faculty;
                List<StudentGroup> groups = _repo
                    .GroupsInFaculties
                    .GetFiltredGroupsInFaculty(gif => gif.Faculty.FacultyId == local2Faculty.FacultyId)
                    .Select(gif => gif.StudentGroup)
                    .ToList();

                Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                Table oTable = oDoc.Tables.Add(wrdRng, 1 + facultyExams.Keys.Count, 1 + groups.Count());

                //oTable.Rows(1).HeadingFormat = True;
                //oTable.ApplyStyleHeadingRows = True;
                oTable.Rows[1].HeadingFormat = -1;
                oTable.ApplyStyleHeadingRows = true;

                oTable.Borders.Enable = 1;

                for (int i = 1; i <= oTable.Rows.Count; i++)
                {
                    oTable.Rows[i].AllowBreakAcrossPages = (int)MsoTriState.msoFalse;
                }


                oTable.Cell(1, 1).Range.Text = "Дата";
                oTable.Cell(1, 1).Range.ParagraphFormat.Alignment =
                        WdParagraphAlignment.wdAlignParagraphCenter;
                for (var column = 1; column <= groups.Count(); column++)
                {
                    oTable.Cell(1, column + 1).Range.Text = groups[column - 1].Name;
                    oTable.Cell(1, column + 1).Range.ParagraphFormat.Alignment =
                        WdParagraphAlignment.wdAlignParagraphCenter;
                }

                for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++)
                {
                    oTable.Cell(row, 1).Range.Text = facultyExams.Keys.ElementAt(row - 2).ToString("dd MMMM yyyy", CultureInfo.CreateSpecificCulture("ru-RU"));
                    oTable.Cell(row, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                    oTable.Cell(row, 1).Range.ParagraphFormat.Alignment =
                        WdParagraphAlignment.wdAlignParagraphCenter;
                }

                for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++)
                {
                    DateTime currentDate = facultyExams.Keys.ElementAt(row - 2);

                    for (var column = 1; column <= groups.Count; column++)
                    {
                        if (facultyExams.ContainsKey(currentDate))
                        {
                            if (facultyExams[currentDate].ContainsKey(groupIds[column - 1]))
                            {
                                var eventCount = facultyExams[currentDate][groupIds[column - 1]].Count;

                                oTable.Cell(row, column + 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                                var timeTable = oDoc.Tables.Add(oTable.Cell(row, column + 1).Range, 1, 1);
                                timeTable.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow);
                                if (eventCount > 1)
                                {
                                    for (int i = 1; i < eventCount; i++)
                                    {
                                        timeTable.Rows.Add();
                                    }
                                }

                                for (int i = 0; i < eventCount; i++)
                                {
                                    string cellText = "";

                                    var evt = facultyExams[currentDate][groupIds[column - 1]][i];

                                    // Консультация || Экзамен                                                                
                                    if (evt.IsExam)
                                    {
                                        cellText += "Экзамен";
                                    }
                                    else
                                    {
                                        cellText += "Консультация";
                                    }

                                    cellText += Environment.NewLine;
                                    cellText += evt.DisciplineName + Environment.NewLine;
                                    cellText += evt.TeacherFio + Environment.NewLine;
                                    cellText += evt.Time.ToString("H:mm") + Environment.NewLine;
                                    cellText += evt.Auditorium;

                                    oPara1 = oDoc.Content.Paragraphs.Add(timeTable.Cell(i + 1, 1).Range);
                                    oPara1.Range.Font.Size = 10;
                                    oPara1.Format.SpaceAfter = 0;
                                    oPara1.Range.Text = cellText;

                                    if (i != eventCount - 1)
                                    {
                                        timeTable.Cell(i + 1, 1).Borders[WdBorderType.wdBorderBottom].Visible = true;
                                    }
                                }
                            }
                        }
                    }
                }


                oTable.Columns[1].Width = oWord.CentimetersToPoints(3);
                for (int i = 0; i < groups.Count; i++)
                {
                    oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(16f / groups.Count);
                }

                oTable.Rows.Alignment = WdRowAlignment.wdAlignRowCenter;

                Paragraph oPara2 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara2.Range.Font.Size = 12;
                oPara2.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara2.Range.Text = "";
                oPara2.Format.SpaceAfter = 0;
                oPara2.Range.InsertParagraphAfter();


                var headUchOtdNameOption = _repo
                    .ConfigOptions
                    .GetFirstFiltredConfigOption(co => co.Key == "Начальник учебного отдела");
                var headUchOtdName = (headUchOtdNameOption == null) ? "" : headUchOtdNameOption.Value;

                oPara2 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara2.Range.Font.Size = 12;
                oPara2.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara2.Range.Text = "Начальник учебного отдела\t\t" + "_________________  " + headUchOtdName;
                oPara2.Format.SpaceAfter = 0;
                oPara2.Range.InsertParagraphAfter();
                oPara2.Range.InsertParagraphAfter();

                oPara2 =
                    oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara2.Range.Font.Size = 12;
                oPara2.Format.LineSpacing = oWord.LinesToPoints(1);
                oPara2.Range.Text = faculty.SessionSigningTitle + "\t\t_________________  " + faculty.DeanSigningSessionSchedule;
                oPara2.Format.SpaceAfter = 0;
                oPara2.Range.InsertParagraphAfter();
                oPara2.Range.InsertParagraphAfter();

                if (faculty.FacultyId != faculties.OrderBy(f => f.SortingOrder).Last().FacultyId)
                {
                    oDoc.Words.Last.InsertBreak(WdBreakType.wdPageBreak);
                }

                System.Windows.Forms.Application.DoEvents();
            }

            //object fileName = Application.StartupPath + @"\Export2.docx";

            //oDoc.SaveAs(ref fileName);

            //oWord.Quit();

        }