示例#1
0
        private void chkSpell_Click(object sender, EventArgs e)
        {
            Word.Application app = new Word.Application();

            int errors = 0;

            //don't show word doing all the work
            app.Visible = false;

            //setting variables that are equivalent to null.
            object template     = Missing.Value;
            object newTemplate  = Missing.Value;
            object documentType = Missing.Value;
            object visible      = true;

            //initalize a document
            Word._Document doc1 = app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);

            //a counter token
            int i = 0;

            //a variable to hold the output
            string[] holder = Regex.Split(txtIssue.Text, "\r\n");


            while (holder.Length > i)
            {
                doc1.Words.First.InsertBefore(holder[i]);

                Word.ProofreadingErrors spellErrorsColl = doc1.SpellingErrors;
                errors = spellErrorsColl.Count;

                object optional = Missing.Value;

                doc1.CheckSpelling(ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional);

                object first = 0;
                object last  = doc1.Characters.Count - 1;

                holder[i] = doc1.Range(ref first, ref last).Text;
                Word.Range deleteme = doc1.Range(ref first, ref last);
                deleteme.Delete(ref optional, ref optional);

                i = i + 1;
            }
            txtIssue.Text = "";
            foreach (string line in holder)
            {
                txtIssue.Text += line + "\r\n";
            }



            object saveChanges    = false;
            object originalFormat = Missing.Value;
            object routeDocument  = Missing.Value;

            app.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
        }
        protected void btnCheck_Click(object sender, EventArgs e)
        {
            // Prevent multiple checker windows.
            if (applicationWord != null)
            {
                return;
            }

            applicationWord = new Microsoft.Office.Interop.Word.Application();
            int errors = 0;

            if (tbInput.Text.Length > 0)
            {
                object template     = Missing.Value;
                object newTemplate  = Missing.Value;
                object documentType = Missing.Value;
                object visible      = true;

                // Define a MS Word Document, then we use this document to calculate errors number and
                // invoke document's CheckSpelling method.
                Microsoft.Office.Interop.Word._Document documentCheck = applicationWord.Documents.Add(ref template,
                                                                                                      ref newTemplate, ref documentType, ref visible);
                applicationWord.Visible = false;
                documentCheck.Words.First.InsertBefore(tbInput.Text);
                Microsoft.Office.Interop.Word.ProofreadingErrors spellErrorsColl = documentCheck.SpellingErrors;
                errors = spellErrorsColl.Count;

                object optional = Missing.Value;
                documentCheck.Activate();
                documentCheck.CheckSpelling(ref optional, ref optional, ref optional, ref optional, ref optional, ref optional,
                                            ref optional, ref optional, ref optional, ref optional, ref optional, ref optional);
                documentCheck.LanguageDetected = true;


                // When users close the dialog, the error message will be displayed.
                if (errors == 0)
                {
                    lbMessage.Text = "No errors";
                }
                else
                {
                    lbMessage.Text = "Total errors num:" + errors;
                }

                // Replace misspelled words of TextBox.
                object first = 0;
                object last  = documentCheck.Characters.Count - 1;
                tbInput.Text = documentCheck.Range(ref first, ref last).Text;
            }

            object saveChanges    = false;
            object originalFormat = Missing.Value;
            object routeDocument  = Missing.Value;

            ((_Application)applicationWord).Quit(ref saveChanges, ref originalFormat, ref routeDocument);
            applicationWord = null;
        }
示例#3
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            var app = new Word.Application();

            var errors = 0;

            if (textBox1.Text.Length > 0)
            {
                app.Visible = false;

                // Setting these variables is comparable to passing null to the function.
                // This is necessary because the C# null cannot be passed by reference.
                object template     = Missing.Value;
                object newTemplate  = Missing.Value;
                object documentType = Missing.Value;
                object visible      = true;

                Word._Document doc1 = app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);
                doc1.Words.First.InsertBefore(textBox1.Text);
                Word.ProofreadingErrors spellErrorsColl = doc1.SpellingErrors;
                errors = spellErrorsColl.Count;

                object optional = Missing.Value;

                doc1.CheckSpelling(
                    ref optional, ref optional, ref optional, ref optional, ref optional, ref optional,
                    ref optional, ref optional, ref optional, ref optional, ref optional, ref optional);

                label1.Text = $"{errors} errors corrected ";
                object first = 0;
                object last  = doc1.Characters.Count - 1;
                textBox1.Text = doc1.Range(ref first, ref last).Text;
            }

            object saveChanges    = false;
            object originalFormat = Missing.Value;
            object routeDocument  = Missing.Value;

            app.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
        }
示例#4
0
        private void BtnGo_Click(object sender, RoutedEventArgs e)
        {
            string en = GetString(rtbEn);
            string ru = GetString(rtbRu);

            if (string.IsNullOrWhiteSpace(en) && string.IsNullOrWhiteSpace(ru))
            {
                return;
            }
            // Parse
            var ens   = ParseSentences(en);
            var rus   = ParseSentences(ru);
            int nRows = ens.Count > rus.Count ? ens.Count : rus.Count;

            CreateWordDocument();
            if (m_app == null)
            {
                return;
            }
            object start    = 0;
            object end      = 0;
            Range  curRange = m_doc.Range(ref start, ref end);

            Microsoft.Office.Interop.Word.Table table = m_doc.Tables.Add(curRange, nRows, 2, ref missingObj, ref missingObj);
            table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;
            for (int i = 0; i < ens.Count; i++)
            {
                var range = table.Cell(i + 1, 1).Range;
                range.Text = ens[i];
            }
            for (int i = 0; i < rus.Count; i++)
            {
                var range = table.Cell(i + 1, 2).Range;
                range.Text = rus[i];
            }

            m_app.Visible = true;
        }
示例#5
0
        private void MakeTable(IEnumerable <object> objects)
        {
            int countColumns = 0;
            int countRows    = 0;

            foreach (var column in columns)
            {
                countColumns++;
            }
            foreach (var o in objects)
            {
                countRows++;
            }
            object start        = 0;
            object end          = 0;
            Range  currentRange = document.Range(ref start, ref end);

            table = document.Tables.Add(currentRange, countRows + 2, countColumns, ref missingObj, ref missingObj);
            table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;
            MakeHeader(table);
            AddData(table, objects);
        }
示例#6
0
        private void saveDoc(string ext, string extName, string fullExtName, Word.WdSaveFormat saveFormat)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter       = fullExtName + "|*" + ext;
            sfd.Title        = "Save an " + ext + " file";
            sfd.AddExtension = true;
            sfd.DefaultExt   = extName;

            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            Object templatePathObj = sfd.FileName;
            Object fileForm        = ext;

            _application = new Word.Application();
            try
            {
                _document = _application.Documents.Add(ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj);
            }
            catch (Exception error)
            {
                this.closeDoc();
                throw error;
            }
            object start = 0;
            object end   = 0;

            _currentRange        = _document.Range(ref start, ref end);
            _currentRange.Text   = textBox.Text;
            _application.Visible = false;

            _document.SaveAs(ref templatePathObj, saveFormat, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj);
            closeDoc();
        }
示例#7
0
        private Boolean next_occur(string search_font, ref int start_pos, ref int end_pos)
        {
            Word.Range oRange;
            Word.Font  oFont;
            int        length, pos;
            object     position;

            length = oDoc.Characters.Count;
            if (end_pos == (length - 1))
            {
                //end of file
                return(false);
            }
            else
            {
                pos = end_pos;
            }

            // find the beginning of the next occurance of the search font

            while (true)
            {
                position = pos;
                oRange   = oDoc.Range(ref position, ref position);
                oFont    = oRange.Font;
                if (oFont.Name.Equals(search_font))
                {
                    break;
                }
                else
                {
                    pos++;
                }
                if (pos == length)
                {
                    // reached end of file
                    return(false);
                }
            }

            start_pos = pos;

            // find the end of this occurance

            while (true)
            {
                position = pos;
                oRange   = oDoc.Range(ref position, ref position);
                oFont    = oRange.Font;
                if (!oFont.Name.Equals(search_font))
                {
                    break;
                }
                else
                {
                    pos++;
                }
                if (pos == length)
                {
                    pos--;
                    break;
                }
            }

            end_pos = pos;

            return(true);
        }
示例#8
0
        private void vacationButton_Click(object sender, EventArgs e)
        {
            Object missingObj = System.Reflection.Missing.Value;
            Object falseObj   = false;

            //создаем обьект приложения word
            application = new Word.Application();
            // создаем путь к файлу
            string path            = Path.GetFullPath(@"Данные\Шаблоны\Увольняемые (шаблон).docx");
            Object templatePathObj = path;

            //Новая форма прогресса
            Progress prgfrm = new Progress();

            prgfrm.Show();

            prgfrm.label1.Text = "Запуск процесса Word";

            // если вылетим не этом этапе, приложение останется открытым
            try
            {
                document = application.Documents.Add(ref templatePathObj, ref missingObj, ref missingObj, ref missingObj);
            }
            catch (Exception error)
            {
                document.Close(ref falseObj, ref missingObj, ref missingObj);
                application.Quit(ref missingObj, ref missingObj, ref missingObj);
                document    = null;
                application = null;
                throw error;
            }

            prgfrm.label1.Text = "Сортировка списка увольняемых";



            //создаем новый лист для списка увольнения, чтобы его отсортировать
            List <string> sortList = new List <string>();

            for (int i = 0; i < uvalParams.Count; i++)
            {
                for (int j = 0; j < tableLSDataGridView1.RowCount - 1; j++)
                {
                    if (uvalParams[i].id == allKorshuns[0, j])
                    {
                        string mergedStr = "";
                        //время увольнения
                        mergedStr += uvalParams[i].time + "*";
                        //добавляем звание
                        mergedStr += allKorshuns[1, j] + "*";
                        //добавляем фамилию и первую букву имени и отчества
                        mergedStr += allKorshuns[3, j] + allKorshuns[4, j].Substring(0, 1) + "." + allKorshuns[5, j].Substring(0, 1) + ".*";
                        //телефон
                        mergedStr += allKorshuns[7, j];


                        sortList.Add(mergedStr);
                        break;
                    }
                }
            }
            sortList.Sort();

            prgfrm.progressBar1.Value = 5;
            prgfrm.label1.Text        = "Заполнение списка увольняемых";
            int stepValueForUval = 75 / sortList.Count;

            //заполняем таблицу в документе
            for (int i = 0; i < sortList.Count; i++)
            {
                string[] split = new string[4];
                split = sortList[i].Split(Convert.ToChar("*"));

                if (i != 0)
                {
                    document.Tables[1].Rows.Add(ref missingObj);
                }

                document.Tables[1].Cell(i + 6, 2).Select(); //+6 потому что заполнение начинается с 6 строки таблицы
                application.Selection.TypeText(split[1]);

                document.Tables[1].Cell(i + 6, 3).Select();
                application.Selection.TypeText(split[2]);

                document.Tables[1].Cell(i + 6, 4).Select();
                application.Selection.TypeText(split[3]);

                document.Tables[1].Cell(i + 6, 5).Select();
                application.Selection.TypeText(split[0]);

                prgfrm.progressBar1.Value += stepValueForUval;
            }


            //выбираем закладки и вставляем туда текст
            document.Bookmarks["date2"].Select();
            string date = monthCalendar1.SelectionStart.ToLongDateString();

            date = '\u00ab' + monthCalendar1.SelectionStart.Day.ToString() + '\u00bb' + date.Substring(date.IndexOf(' '));
            application.Selection.TypeText(date);

            document.Bookmarks["date1"].Select();
            application.Selection.TypeText(date.Remove(date.Count() - 3));

            //составляем путь для сохранения временного файла
            string strVr           = Environment.CurrentDirectory + @"\Данные\Шаблоны\temp.doc";
            Object pathToSaveObjVr = strVr;

            //сохраняем во временный файл
            document.SaveAs(ref pathToSaveObjVr, Word.WdSaveFormat.wdFormatDocument, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj);


            document.Close(ref falseObj, ref missingObj, ref missingObj);
            application.Quit(ref missingObj, ref missingObj, ref missingObj);
            document    = null;
            application = null;

            prgfrm.label1.Text = "Заполнение списков отпускников";

            //документы с отпускниками
            if (checkBox4.Checked && vacParamsDay.Count > 0)
            {
                List <vacParam> vacatorsDayAll = vacParamsDay;

                while (true)
                {
                    DateTime startDate = vacatorsDayAll[0].startDate;
                    foreach (vacParam vp in vacatorsDayAll)
                    {
                        if (vp.startDate > startDate)
                        {
                            startDate = vp.startDate;
                        }
                    }

                    List <vacParam> vacatorsNow = new List <vacParam>();
                    for (int i = 0; i < vacatorsDayAll.Count; i++)
                    {
                        if (vacatorsDayAll[i].startDate == startDate)
                        {
                            vacatorsNow.Add(vacatorsDayAll[i]);
                            vacatorsDayAll.RemoveAt(i);
                            i--;
                        }
                    }

                    VacationDoc(vacatorsNow);

                    if (prgfrm.progressBar1.Value <= 90) // коряво, можно сделать красиво, но это добавится еще кусок кода строк на 10 и ухудшится производительность
                    {
                        prgfrm.progressBar1.Value += 5;
                    }

                    if (vacatorsDayAll.Count == 0)
                    {
                        break;
                    }
                }
            }

            application = new Word.Application();
            document    = application.Documents.Add(ref pathToSaveObjVr, ref missingObj, ref missingObj, ref missingObj);

            prgfrm.progressBar1.Value = 95;
            prgfrm.label1.Text        = "Исправление ошибок форматирования";
            //Исправление ошибок форматирования, которые появляются хер знает почему при объединении файлов
            //увеличивается шрифт в таблице
            int tablesCount = document.Tables.Count;

            Word.Range rng = document.Tables[tablesCount].Range;
            rng.Font.Size = 11;
            //и подчеркивается заголовок
            rng = document.Range();
            rng.Font.Underline = Word.WdUnderline.wdUnderlineNone;
            //Прям очень коряво. Но кому сейчас легко?

            //составляем путь для сохранения файла
            string str = Environment.CurrentDirectory;

            str = str.Remove(str.LastIndexOf((@"\"))); //поднимаемся на один каталог выше расположения программы
            string nameOfDirectory = @"\5. Увольняемые\";

            if (!Directory.Exists(str + nameOfDirectory))
            {
                Directory.CreateDirectory(str + nameOfDirectory);
            }

            int    weekNumber = GetWeekNumber(monthCalendar1.SelectionStart) + 1;
            string nameOfFile = weekNumber + ".Увольняемые(" + monthCalendar1.SelectionStart.ToShortDateString() + ").doc";

            str = str + nameOfDirectory + nameOfFile;
            Object pathToSaveObj = str;

            prgfrm.progressBar1.Value = 100;
            prgfrm.label1.Text        = "Готово!";
            if (File.Exists(str))
            {
                DialogResult dlr =
                    MessageBox.Show("Файл с этой датой уже существует. Перезаписать?", "Файл уже существует", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlr == DialogResult.Yes)
                {
                    document.SaveAs(ref pathToSaveObj, Word.WdSaveFormat.wdFormatDocument, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj);
                }
                else
                {
                    //сохраняем во временный файл
                    document.SaveAs(ref pathToSaveObjVr, Word.WdSaveFormat.wdFormatDocument, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj);
                }
            }
            else
            {
                document.SaveAs(ref pathToSaveObj, Word.WdSaveFormat.wdFormatDocument, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj);
            }


            application.Visible = true;

            UpdateVacatorsList();

            prgfrm.Close();
        }
示例#9
0
        public static void CreateBallots(Tournament tournament, DataContext context, Guid roundId)
        {
            SqlHelper helper = new SqlHelper(tournament.Database);

            Round round = helper.GetRound(roundId).Result;

            string motion = round.Motion;

            List <Debate> debates = helper.GetDebates(roundId).Result;

            string directory = Path.Combine(Path.GetDirectoryName(tournament.Location), tournament.Name, string.Format("Round {0}", round.RoundNumber));

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

            string ballotsDirectory = Path.Combine(directory, "ballots");

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

            foreach (Debate debate in debates)
            {
                List <SpeakerDraw> speakerDraws = helper.GetSpeakerDrawsByDebate(debate.DebateId).Result;
                List <JudgeDraw>   judgeDraws   = helper.GetJudgeDrawsByDebate(debate.DebateId).Result;

                Venue venue = context.Venues.First(v => v.VenueId.Equals(debate.VenueId));

                Word._Application wordApplication = new Word.Application()
                {
                    Visible = false
                };
                wordApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
                object         filename     = Path.Combine(Path.GetDirectoryName(tournament.Location), tournament.Name, "lib", "ballot.docx");
                Word._Document wordDocument = wordApplication.Documents.Open(ref filename);
                wordDocument.Activate();
                Word.Range content = wordDocument.Range();

                Dictionary <string, string> findReplaces = new Dictionary <string, string>();
                findReplaces.Add("#t", tournament.Name);
                findReplaces.Add("#v", venue.Name);
                string chairJudge = judgeDraws.OrderBy(j => j.Number).Select(jd => context.Judges.First(j => j.JudgeId.Equals(jd.JudgeId))).First().Name;
                findReplaces.Add("#chair", chairJudge);

                findReplaces.Add("#j", string.Join(", ", judgeDraws.OrderBy(j => j.Number).Select(a => context.Judges.First(j => j.JudgeId.Equals(a.JudgeId)).Name)));
                findReplaces.Add("#r", round.RoundNumber.ToString());
                findReplaces.Add("#m", motion);

                SpeakerDraw og        = speakerDraws.First(sd => sd.Position.Equals(Position.OpeningGovernment));
                Speaker     ogSpeaker = context.Speakers.First(sd => og.SpeakerId.Equals(sd.SpeakerId));
                findReplaces.Add("#og", context.Speakers.First(s => s.SpeakerId.Equals(og.SpeakerId)).Name);
                findReplaces.Add("#iog", context.Institutions.First(i => i.InstitutionId.Equals(ogSpeaker.InstitutionId)).Name);

                SpeakerDraw oo        = speakerDraws.First(sd => sd.Position.Equals(Position.OpeningOpposition));
                Speaker     ooSpeaker = context.Speakers.First(sd => oo.SpeakerId.Equals(sd.SpeakerId));
                findReplaces.Add("#oo", context.Speakers.First(s => s.SpeakerId.Equals(oo.SpeakerId)).Name);
                findReplaces.Add("#ioo", context.Institutions.First(i => i.InstitutionId.Equals(ooSpeaker.InstitutionId)).Name);

                SpeakerDraw sg        = speakerDraws.First(sd => sd.Position.Equals(Position.SecondGovernment));
                Speaker     sgSpeaker = context.Speakers.First(sd => sg.SpeakerId.Equals(sg.SpeakerId));
                findReplaces.Add("#sg", context.Speakers.First(s => s.SpeakerId.Equals(sg.SpeakerId)).Name);
                findReplaces.Add("#isg", context.Institutions.First(i => i.InstitutionId.Equals(sgSpeaker.InstitutionId)).Name);

                SpeakerDraw so        = speakerDraws.First(sd => sd.Position.Equals(Position.SecondOpposition));
                Speaker     soSpeaker = context.Speakers.First(sd => so.SpeakerId.Equals(sd.SpeakerId));
                findReplaces.Add("#so", context.Speakers.First(s => s.SpeakerId.Equals(so.SpeakerId)).Name);
                findReplaces.Add("#iso", context.Institutions.First(i => i.InstitutionId.Equals(soSpeaker.InstitutionId)).Name);

                SpeakerDraw cg        = speakerDraws.First(sd => sd.Position.Equals(Position.ClosingGovernment));
                Speaker     cgSpeaker = context.Speakers.First(sd => cg.SpeakerId.Equals(sd.SpeakerId));
                findReplaces.Add("#cg", context.Speakers.First(s => s.SpeakerId.Equals(cg.SpeakerId)).Name);
                findReplaces.Add("#icg", context.Institutions.First(i => i.InstitutionId.Equals(cgSpeaker.InstitutionId)).Name);

                SpeakerDraw co        = speakerDraws.First(sd => sd.Position.Equals(Position.ClosingOpposition));
                Speaker     coSpeaker = context.Speakers.First(sd => co.SpeakerId.Equals(sd.SpeakerId));
                findReplaces.Add("#co", context.Speakers.First(s => s.SpeakerId.Equals(co.SpeakerId)).Name);
                findReplaces.Add("#ico", context.Institutions.First(i => i.InstitutionId.Equals(coSpeaker.InstitutionId)).Name);

                foreach (KeyValuePair <string, string> keyValuePair in findReplaces)
                {
                    content.Find.Execute(FindText: keyValuePair.Key, Replace: Word.WdReplace.wdReplaceAll, ReplaceWith: keyValuePair.Value);
                }

                object ballotFilename = Path.Combine(ballotsDirectory, string.Format("{0}.doc", venue.Name));

                wordDocument.SaveAs(ref ballotFilename);

                object save = Word.WdSaveOptions.wdDoNotSaveChanges;

                wordDocument.Close(ref save);
                wordApplication.Quit();
            }
        }