Пример #1
0
        private void button1_Click(object sender, EventArgs e)
        {
            Word.Document wd = new Word.Document();
            wd.Activate();
            Object start = Type.Missing;
            Object end   = Type.Missing;

            Word.Range rng = wd.Range(ref start, ref end);
            Object     defaultTableBehavior = Type.Missing;
            Object     autoFitBehavior      = Type.Missing;
            object     missing = System.Type.Missing;

            Word.Table tbl = wd.Tables.Add(rng, 1, 7, ref missing, ref missing);
            SetHeadings(tbl.Cell(1, 1), "Title 1");
            SetHeadings(tbl.Cell(1, 2), "Title 2");
            SetHeadings(tbl.Cell(1, 3), "Title 3");
            SetHeadings(tbl.Cell(1, 4), "Title 4");
            SetHeadings(tbl.Cell(1, 5), "Title 5");
            SetHeadings(tbl.Cell(1, 6), "Title 6");
            SetHeadings(tbl.Cell(1, 7), "Title 7");
            for (int i = 0; i < lecturerData.Rows.Count; i++)
            {
                Word.Row newRow = wd.Tables[1].Rows.Add(ref missing);
                newRow.Range.Font.Bold = 0;
                newRow.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                newRow.Cells[1].Range.Text             = lecturerData.Rows[i][0].ToString();
                newRow.Cells[2].Range.Text             = lecturerData.Rows[i][1].ToString();
                newRow.Cells[3].Range.Text             = lecturerData.Rows[i][2].ToString();
                newRow.Cells[4].Range.Text             = lecturerData.Rows[i][3].ToString();;
                newRow.Cells[5].Range.Text             = lecturerData.Rows[i][4].ToString();
                newRow.Cells[6].Range.Text             = lecturerData.Rows[i][5].ToString();
                newRow.Cells[7].Range.Text             = lecturerData.Rows[i][6].ToString();
            }
        }
Пример #2
0
 protected void SetFontRow(Word.Row row)
 {
     row.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
     row.Range.Font.Bold   = 0;
     row.Range.Font.Italic = 0;
     row.Range.Font.Name   = "Times New Roman";
 }
Пример #3
0
        public void copyTableData(List <int> oldTablesNumbers, int newTableNumber, ref Dictionary <string, string> dict, ref Dictionary <string, string> constantsDict, ref Word.Document newDoc)
        {
            string oldFilePath = constantsDict["Reading Old Documents Path"] + "\\INT-002-002-" + dict["OldServiceID"] + "-DTD " + dict["OldServiceSubject"] + ".docx";

            Console.WriteLine(oldFilePath);
            Word.Document oldDoc          = wordApp.Documents.Open(oldFilePath);
            Word.Table    newRequestTable = newDoc.Tables[newTableNumber];
            int           index           = 2;

            foreach (int k in oldTablesNumbers)
            {
                Console.WriteLine("Reading old Table Number " + k);
                Word.Table oldRequestTable = oldDoc.Tables[k];
                Word.Rows  oldRequestRows  = oldRequestTable.Rows;
                for (int i = 3; i <= oldRequestRows.Count - 1; i++)
                {
                    newRequestTable.Rows.Add(newRequestTable.Rows[index]);
                    Word.Row oldRow = oldRequestRows[i];
                    for (int j = 1; j <= oldRow.Cells.Count; j++)
                    {
                        Word.Cell cell1 = newRequestTable.Cell(index, j);
                        //Console.WriteLine(i + " " + j + " " + oldRequestTable.Cell(i, j).Range.Text);
                        cell1.Range.Text = oldRequestTable.Cell(i, j).Range.Text;
                    }
                    index++;
                }
            }
            newRequestTable.Rows[index].Delete();
            oldDoc.Close();
        }
Пример #4
0
        /// <summary>
        /// Does the actual work of adding the row into the table in the document
        /// </summary>
        /// <param name="values">list of values used to create the row in the table</param>
        /// <param name="table">the table to modify</param>
        private void AppendRowToTable(List <string> values, ref Word.Table table)
        {
            Word.Row row = table.Rows.Add(System.Reflection.Missing.Value);
            int      i   = 0;

            foreach (string item in values)
            {
                row.Cells[++i].Range.Text = item;
            }
        }
Пример #5
0
 private bool addRows(Word.Row oRow, multiLOEP tempRow)
 {
     if (tempRow.startPage == "Empty")
     {
         return(false);
     }
     oRow.Cells[1].Range.Text = tempRow.startPage;
     oRow.Cells[2].Range.Text = tempRow.endPage;
     oRow.Cells[3].Range.Text = tempRow.rev;
     oRow.Cells[4].Range.Text = tempRow.date;
     return(true);
 }
Пример #6
0
        private void btnOM_Click(object sender, EventArgs e)
        {
            //Inserts a table with 300 rows using automation
            object bookmarkName = "bkAutomation";

            if (!this.Bookmarks.Exists("bkAutomation"))
            {
                MessageBox.Show("Please create bookmark with name bkAutomation");
                return;
            }
            Word.Bookmark tblBookmark = this.Bookmarks.get_Item(ref bookmarkName);
            if (tblBookmark.Range.Tables.Count > 0)
            {
                MessageBox.Show("Table already exists.Please delete this table.");
                return;
            }
            Word.Range range = tblBookmark.Range;
            Word.Table table =
                this.Tables.Add(range, 1, 3, ref missing, ref missing);
            table.Borders.InsideLineStyle =
                Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            table.Borders.OutsideLineStyle =
                Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            for (int i = 0; i < 301; i++)
            {
                wordRow = table.Rows.Add(ref missing);
                foreach (Cell cell in wordRow.Cells)
                {
                    ContentControl contentcontrol =
                        cell.Range.ContentControls.Add
                            (WdContentControlType.wdContentControlRichText, ref missing);
                }
            }
            object tableRange = table.Range;

            //Add bookmark back to the table
            table.Range.Bookmarks.Add("bkAutomation", ref tableRange);
        }
Пример #7
0
        public void AddRowToTable()
        {
            Word.Row row = table.Rows.Add();

            // порядковый номер строки
            row.Cells[1].Range.Text = (CurrentRow++).ToString();

            // для каждого индекса дефолтного значения в строке заполняем дефолтным значением
            int numDefaultValues = data.indicesDefaultValues.Count;

            for (int j = 0; j < numDefaultValues; j++)
            {
                row.Cells[data.indicesDefaultValues[j]].Range.Text = data.valuesDefaultValues[j];
            }

            // кастомные значения
            int numCustomColumns = data.indicesCustomValues.Count;

            for (int k = 0; k < numCustomColumns; k++)
            {
                row.Cells[data.indicesCustomValues[k]].Range.Text = data.valuesCustomValues[CurrentRow - 2][k];
            }
        }
Пример #8
0
        private void MakeHeader(Table table)
        {
            Microsoft.Office.Interop.Word.Row  row       = table.Rows[1];
            Microsoft.Office.Interop.Word.Cell firstCell = row.Cells[1];
            foreach (Microsoft.Office.Interop.Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }
            firstCell.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalTop;
            Range nameTableRange = table.Cell(1, 1).Range;

            nameTableRange.Text = "Отчет";
            Range headerRange;

            for (int i = 0; i < table.Columns.Count; i++)
            {
                headerRange      = table.Cell(2, i + 1).Range;
                headerRange.Text = columns[i];
            }
        }
        protected void PasteTable(List <List <string> > data, string bookmark)
        {
            Word.Range range = _document.Bookmarks.get_Item(bookmark).Range;
            range.Text = "";
            int rowsCount = data.Count;
            int colsCount = data[0].Count;

            Word.Table table = _document.Tables.Add(range, rowsCount, colsCount, ref missing, ref missing);
            table.Borders.Enable = 1;
            table.AllowAutoFit   = true;
            table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);
            object styleTableText = "Table text";

            for (int r = 0; r < rowsCount; r++)
            {
                Word.Row row = table.Rows[r + 1];
                for (int c = 0; c < colsCount; c++)
                {
                    Word.Cell cell = row.Cells[c + 1];
                    cell.Range.set_Style(ref styleTableText);
                    //Header row
                    if (cell.RowIndex == 1)
                    {
                        cell.Range.Text        = data[r][c];
                        cell.Range.Font.Bold   = 1;
                        cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    }
                    //Data row
                    else
                    {
                        cell.Range.Text = data[r][c];
                    }
                }
            }
        }
Пример #10
0
        private void buildTable()
        {
            int rowcnt;
            int t       = 0;
            int p       = 0;
            int maxRows = Application.ActiveDocument.InlineShapes.Count / 2;

            Word.Table oTable = Application.ActiveDocument.Bookmarks["summaryTable"].Range.Tables[1];
            if (oTable.Rows.Count > 1)
            {
                for (p = oTable.Rows.Count; p > 1; p--)
                {
                    if (p != 1)
                    {
                        oTable.Rows[p].Delete();
                    }
                }
            }
            for (rowcnt = 1; rowcnt <= maxRows; rowcnt++)
            {
                oTable.Rows.Add();
                Word.Row oNewRow = oTable.Rows[oTable.Rows.Count];
                oNewRow.Cells[1].Range.Text = tryDictionaryKey("ImageDate" + rowcnt);
                oNewRow.Cells[2].Range.Text = rowcnt.ToString();
                oNewRow.Cells[3].Range.Text = tryDictionaryKey("Priority Rating" + rowcnt);
                oNewRow.Cells[4].Range.Text = tryDictionaryKey("Location" + rowcnt);
                oNewRow.Cells[5].Range.Text = tryDictionaryKey("Equipment" + rowcnt);
                oNewRow.Cells[6].Range.Text = tryDictionaryKey("P0" + rowcnt);
                string d1     = tryDictionaryKey(("P0" + rowcnt).ToString());
                double d1d    = Convert.ToDouble(d1.Remove(d1.Length - 2).Trim());
                string d2     = tryDictionaryKey(("P1" + rowcnt).ToString());
                double d2d    = Convert.ToDouble(d2.Remove(d2.Length - 2).Trim());
                double delta1 = d1d - d2d;
                oNewRow.Cells[7].Range.Text = delta1.ToString();
            }
        }
Пример #11
0
        /// <summary>
        /// 填充Table
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        private bool SetTable(WordElement element)
        {
            if (element.Range.Tables != null && element.Range.Tables.Count > 0)
            {
                string startWith = "table_" + element.Level.ToString() + "_";
                foreach (Word.Table table in element.Range.Tables)
                {
                    if (!string.IsNullOrEmpty(table.Title) && table.Title.StartsWith(startWith))
                    {
                        WordElement tableElement = new WordElement(null, table.Title, element.DataRow);

                        TableConfig config = new TableConfig(table.Descr);

                        object    dataRowTemplate = table.Rows[config.DataRow];
                        Word.Row  SummaryRow      = null;
                        DataRow   SummaryDataRow  = null;
                        DataTable dt       = dataSource.Tables[tableElement.TableIndex];
                        DataRow[] dataRows = dataSource.Tables[tableElement.TableIndex].Select(tableElement.GroupByString);;

                        if (config.SummaryRow > 0)
                        {
                            SummaryRow     = table.Rows[config.SummaryRow];
                            SummaryDataRow = dt.Select(string.IsNullOrEmpty(tableElement.GroupByString) ? config.SummaryFilter : tableElement.GroupByString + " and  " + config.SummaryFilter).FirstOrDefault();
                        }

                        foreach (DataRow row in dataRows)
                        {
                            if (row == SummaryDataRow)
                            {
                                continue;
                            }

                            Word.Row newRow = table.Rows.Add(ref dataRowTemplate);
                            for (int j = 0; j < table.Columns.Count; j++)
                            {
                                newRow.Cells[j + 1].Range.Text = row[j].ToString();;
                            }
                        }

                        ((Word.Row)dataRowTemplate).Delete();

                        if (config.SummaryRow > 0 && SummaryDataRow != null)
                        {
                            for (int j = 0; j < SummaryRow.Cells.Count; j++)
                            {
                                string temp = SummaryRow.Cells[j + 1].Range.Text.Trim().Replace("\r\a", "");

                                if (!string.IsNullOrEmpty(temp) && temp.Length > 2 && dt.Columns.Contains(temp.Substring(1, temp.Length - 2)))
                                {
                                    SummaryRow.Cells[j + 1].Range.Text = SummaryDataRow[temp.Substring(1, temp.Length - 2)].ToString();
                                }
                            }
                        }

                        table.Title = tableElement.Name;
                    }
                }
            }

            return(true);
        }
Пример #12
0
        /// <summary>
        /// Load Purchase Order controls from xml file data
        /// </summary>
        /// <returns>Successfully loaded Word document</returns>
        public bool LoadPurchaseOrder()
        {
            try
            {
                xsTaskCode xmlTask = new xsTaskCode();
                xmlTask.ReadXml(Schema.TaskSingleXmlFileName);
                xsTaskCode.TaskRow taskRow = (xsTaskCode.TaskRow)xmlTask.Task.Rows[0];

                #region header
                WriteControl("ContactName", taskRow.ContactName);
                WriteControl("AccountName", taskRow.AccountName);
                WriteControl("InvoiceAddress", taskRow.IsInvoiceAddressNull() ? string.Empty : taskRow.InvoiceAddress);
                WriteControl("TaskCode", taskRow.TaskCode);
                WriteControl("SecondReference", taskRow.IsSecondReferenceNull() ? string.Empty : taskRow.SecondReference);
                WriteControl("NickName", taskRow.NickName);
                WriteControl("TaskTitle", taskRow.IsTaskTitleNull() ? string.Empty : taskRow.TaskTitle);
                WriteControl("DeliveryAddress", taskRow.IsDeliveryAddressNull() ? string.Empty : taskRow.DeliveryAddress);
                WriteControl("Quantity", taskRow.Quantity.ToQuantity());
                WriteControl("UnitOfMeasure", taskRow.UnitOfMeasure);
                WriteControl("ActionOn", taskRow.ActionOn.ToString());
                WriteControl("TotalCharge", taskRow.TotalCharge.ToCurrency());
                WriteControl("TaxRate", taskRow.TaxRate.ToPercentage());
                WriteControl("PaymentTerms", taskRow.PaymentTerms);
                WriteControl("TaskNotes", taskRow.IsTaskNotesNull() ? string.Empty : taskRow.TaskNotes);
                WriteControl("UserName", taskRow.UserName);
                WriteControl("CompanyName", taskRow.CompanyName);
                WriteControl("PaymentTerms", taskRow.PaymentTerms);
                WriteControl("DeliveryAddress", taskRow.DeliveryAddress);
                #endregion

                #region Attributes
                Word.Table attributeTable = null;
                Word.Row   attributeRow   = null;
                object     attribObj      = null;
                int[]      idxAttrib      = new int[] { 1, 2 };

                foreach (Word.Table table in document.Tables)
                {
                    foreach (Word.Row row in table.Rows)
                    {
                        foreach (Word.Cell cell in row.Range.Cells)
                        {
                            foreach (Word.ContentControl ctl in cell.Range.ContentControls)
                            {
                                switch (ctl.Tag)
                                {
                                case "a1":
                                    attributeTable = table;
                                    attribObj      = (object)row;
                                    attributeRow   = row;
                                    idxAttrib[0]   = cell.ColumnIndex;
                                    break;

                                case "a2":
                                    idxAttrib[1] = cell.ColumnIndex;
                                    break;
                                }
                            }
                        }
                        if (attributeRow != null)
                        {
                            break;
                        }
                    }
                    if (attributeRow != null)
                    {
                        break;
                    }
                }

                if (attributeRow != null)
                {
                    var attributes = from tb in xmlTask.Attributes
                                     select tb;

                    foreach (xsTaskCode.AttributesRow row in attributes)
                    {
                        if (((AttributeType)row.AttributeTypeCode == AttributeType.Order) ||
                            ((AttributeType)row.AttributeTypeCode == AttributeType.Quote && (TaskStatus)taskRow.TaskStatusCode == TaskStatus.Pending))

                        {
                            Word.Row newRow = attributeTable.Rows.Add(ref attribObj);
                            newRow.Cells[idxAttrib[0]].Range.Text = row.Attribute;
                            newRow.Cells[idxAttrib[1]].Range.Text = row.AttributeDescription;
                        }
                    }

                    attributeRow.Delete();
                }
                #endregion

                #region Schedule
                Word.Table scheduleTable = null;
                Word.Row   scheduleRow   = null;
                object     scheduleObj   = null;
                int[]      idxSched      = new int[] { 1, 2, 3 };

                foreach (Word.Table table in document.Tables)
                {
                    foreach (Word.Row row in table.Rows)
                    {
                        foreach (Word.Cell cell in row.Range.Cells)
                        {
                            foreach (Word.ContentControl ctl in cell.Range.ContentControls)
                            {
                                switch (ctl.Tag)
                                {
                                case "s1":
                                    scheduleTable = table;
                                    scheduleObj   = (object)row;
                                    scheduleRow   = row;
                                    idxSched[0]   = cell.ColumnIndex;
                                    break;

                                case "s2":
                                    idxSched[1] = cell.ColumnIndex;
                                    break;

                                case "s3":
                                    idxSched[2] = cell.ColumnIndex;
                                    break;
                                }
                            }
                        }
                        if (scheduleRow != null)
                        {
                            break;
                        }
                    }
                    if (scheduleRow != null)
                    {
                        break;
                    }
                }

                if (scheduleRow != null)
                {
                    var schedule = from tb in xmlTask.Schedule
                                   select tb;

                    foreach (xsTaskCode.ScheduleRow row in schedule)
                    {
                        Word.Row newRow = scheduleTable.Rows.Add(ref scheduleObj);
                        newRow.Cells[idxSched[0]].Range.Text = row.Operation;
                        newRow.Cells[idxSched[1]].Range.Text = row.EndOn.ToShortDateString();
                        newRow.Cells[idxSched[2]].Range.Text = row.IsNoteNull() ? string.Empty : row.Note;
                    }

                    scheduleRow.Delete();
                }
                #endregion

                return(true);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, $"{err.Source}.{err.TargetSite.Name}", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
        }
Пример #13
0
        /// <summary>
        /// Generate word document with register of system documents
        /// </summary>
        /// <param name="tv"></param>
        public string RegisterOfSytemDocuments(TreeView tv, string clientFolder)
        {
            object oMissing = System.Reflection.Missing.Value;
            var    pastPlannedActivities = string.Empty;

            //Start Word and create a new document.
            WordNet._Application oWord = new Application {
                Visible = false
            };
            WordNet._Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
                                                         ref oMissing, ref oMissing);

            oDoc.PageSetup.Orientation = WordNet.WdOrientation.wdOrientLandscape;

            PrintToWord(oDoc, "Register of System Documents", 16, 0, FCMWordAlign.CENTER);
            PrintToWord(oDoc, " ", 8, 0);

            // Locate client folder
            //
            string clientFileLocationName = Utils.getFilePathName(@"%TEMPLATEFOLDER%\ClientSource\", "ROS-001 Register Of System Documents.doc");

            FullFileNamePath = clientFileLocationName;
            FileName         = "RegisterOfSystemDocuments.doc";

            if (File.Exists(clientFileLocationName))
            {
                // Delete file
                try
                {
                    File.Delete(clientFileLocationName);
                    uioutput.AddOutputMessage("File replaced: " + clientFileLocationName);
                }
                catch (Exception)
                {
                    uioutput.AddOutputMessage("Error deleting file " + clientFileLocationName);
                    uioutput.AddErrorMessage("Error deleting file " + clientFileLocationName);
                    return(clientFileLocationName);
                }
            }


            // string filename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetTempFileName(), "doc"));
            oDoc.SaveAs(clientFileLocationName);

            string msg = ">>> Generating file... ";

            if (uioutput != null)
            {
                uioutput.AddOutputMessage(msg);
            }

            PrintToWord(oDoc, " ", 8, 1);

            WordNet.Range wrdRng;
            WordNet.Table oTable;

            wrdRng = oDoc.Bookmarks.get_Item(oEndOfDoc).Range;
            int rowCount = 30;

            // Get number of rows for a client document, client document set
            //
            var cds = new BUSClientDocumentSet(Utils.ClientID, Utils.ClientSetID);

            rowCount = cds.DocumentCount;

            if (rowCount < 1)
            {
                return(clientFileLocationName);
            }

            oTable = oDoc.Tables.Add(wrdRng, rowCount, 6, ref vkFalse, ref vkFalse);

            //oTable.Borders.InsideLineWidth = WordNet.WdLineWidth.wdLineWidth050pt;
            //oTable.Borders.InsideColor = WordNet.WdColor.wdColorAutomatic;
            //oTable.Borders.OutsideLineWidth = WordNet.WdLineWidth.wdLineWidth050pt;
            //oTable.Borders.OutsideColor = WordNet.WdColor.wdColorAutomatic;

            oTable.Rows[1].HeadingFormat = -1;

            WordNet.Row headingRow = oTable.Rows[1];

            ApplyHeadingStyle(headingRow.Cells[1], 40);
            headingRow.Cells[1].Range.Text = "";

            ApplyHeadingStyle(headingRow.Cells[2], 30);
            headingRow.Cells[2].Range.Text = "";

            ApplyHeadingStyle(headingRow.Cells[3], 60);
            headingRow.Cells[3].Range.Text = "Document Number";

            ApplyHeadingStyle(headingRow.Cells[4], 50);
            headingRow.Cells[4].Range.Text = "Version";

            ApplyHeadingStyle(headingRow.Cells[5], 300);
            headingRow.Cells[5].Range.Text = "Document Name";

            ApplyHeadingStyle(headingRow.Cells[6], 100);
            headingRow.Cells[6].Range.Text = "Comments";

            int line = 0;

            foreach (var treeNode in tv.Nodes)
            {
                line++;
                WriteLineToRoSD(tv.Nodes[0], oDoc, oTable, prefix: "", parent: "", seqnum: line);
            }


            msg = ">>> End ";
            if (uioutput != null)
            {
                uioutput.AddOutputMessage(msg);
            }

            PrintToWord(oDoc, " ", 12, 1);

            oDoc.Save();
            oDoc.Close();

            oWord.Visible = true;
            oWord.Documents.Open(FileName: clientFileLocationName);
            oWord.Activate();

            return(clientFileLocationName);
        }
Пример #14
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var t = e.Argument as Tuple <string, string, string, string>;

            if (String.IsNullOrWhiteSpace(t.Item2) || String.IsNullOrWhiteSpace(t.Item3)) //вставить проверку, что указаны годы
            {
                MessageBox.Show("Не указаны годы рождения!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (t.Item1 == "")
            {
                MessageBox.Show("Район не задан!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            string select = @"SELECT     Student.name, Student.birth, city.city, Student.street, Student.house, Student.flat, district.district
                                FROM         Student INNER JOIN
                                city ON Student.id_city = city.id INNER JOIN
                                district ON Student.id_district = district.id
                                WHERE id_district = " + ConvertDistrictNameToIdDistrict(t.Item1) +
                            @" AND (prikazNumKval = '') AND (prikazNumOut = '') 
                                   AND (birth >= '01.01." + t.Item2 + "' AND birth <= '31.12." + t.Item3 + @"')
                                ORDER BY name";

            DataSet ds1 = new DataSet();

            try
            {
                ds1 = Util.FillTable("Student", select);
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }

            if (ds1.Tables[0].Rows.Count == 0)
            {
                MessageBox.Show("С указанными данными никого нет!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Word.Application wdApp  = new Word.Application();
            Word.Document    wdDoc  = new Word.Document();
            Object           wdMiss = System.Reflection.Missing.Value;

            wdDoc = wdApp.Documents.Add(ref wdMiss, ref wdMiss, ref wdMiss, ref wdMiss);
            //wdApp.Visible = true; //сначала формируется документ, показывать потом
            wdDoc.PageSetup.LeftMargin   = 40;
            wdDoc.PageSetup.RightMargin  = 25;
            wdDoc.PageSetup.TopMargin    = 20;
            wdDoc.PageSetup.BottomMargin = 20;
            Word.Table tb;
            Word.Range _range;

            int columnsCount = 5;

            tb = wdDoc.Tables.Add(wdApp.Selection.Range, ds1.Tables[0].Rows.Count + 3, columnsCount);
            tb.Columns[1].Width = 40;
            tb.Rows[1].Height   = 40;
            tb.Columns[2].Width = 210;
            tb.Rows[2].Height   = 40;
            tb.Columns[3].Width = 60;
            tb.Rows[3].Height   = 40;
            tb.Columns[4].Width = 140;
            tb.Columns[5].Width = 90;

            Word.Row  row       = tb.Rows[1];
            Word.Cell firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }
            row       = tb.Rows[2];
            firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }

            tb.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wdApp.Selection.Range.Font.Name            = "Times New Roman";
            wdApp.Selection.Range.Font.Size            = 10;
            wdApp.Selection.Cells.VerticalAlignment    = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 0;

            tb.Cell(1, 1).Select();
            wdApp.Selection.Range.Font.Size = 14;
            wdApp.Selection.Font.Bold       = 1;
            tb.Cell(1, 1).Range.Text        = "Список";
            tb.Rows[2].Select();
            wdApp.Selection.Range.Font.Size = 12;
            wdApp.Selection.Font.Bold       = 1;
            tb.Cell(2, 1).Range.Text        = " студентов " + t.Item2 + " - " + t.Item3 +
                                              " г.р. проживающих в " + DistrictForm(t.Item1) + " районе на " + t.Item4 + " года ";

            tb.Rows[3].Select();
            wdApp.Selection.Font.Bold = 1;
            tb.Cell(3, 1).Range.Text  = "№ п/п";
            tb.Cell(3, 2).Range.Text  = "ФИО";
            tb.Cell(3, 3).Range.Text  = "Дата рождения";
            tb.Cell(3, 4).Range.Text  = "Домашний адрес";
            tb.Cell(3, 5).Range.Text  = "Примечание";


            int rowCount  = 3;
            int rowNumber = 0;

            foreach (DataRow str in ds1.Tables[0].Rows)
            {
                rowCount++;
                rowNumber++;
                tb.Cell(rowCount, 1).Range.Text = rowNumber.ToString() + ".";
                tb.Cell(rowCount, 2).Range.Text = str.ItemArray[0].ToString();
                tb.Cell(rowCount, 3).Range.Text = DateTime.Parse(str.ItemArray[1].ToString()).ToShortDateString(); //номер курса считать
                tb.Cell(rowCount, 4).Range.Text = "г." + str.ItemArray[2].ToString() + ", ул." + str.ItemArray[3].ToString() + ", д." +
                                                  str.ItemArray[4].ToString() + ", кв." + str.ItemArray[5].ToString();
            }

            _range = wdDoc.Range(tb.Cell(4, 2).Range.Start, tb.Cell(rowCount, 5).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            _range = wdDoc.Range(tb.Cell(3, 1).Range.Start, tb.Cell(rowCount, columnsCount).Range.End);
            _range.Select();

            /* вызов макроса для отображения границ таблицы
             * Sub Сетка()
             * 'Сетка макрос
             * With Selection.Borders(wdBorderTop)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderLeft)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderBottom)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderRight)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderHorizontal)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderVertical)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * End Sub
             */
            try
            {
                wdApp.Run("Сетка");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " Сетка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }


            //таблица для подписей
            wdApp.Selection.EndOf(Word.WdUnits.wdStory);
            wdApp.Selection.InsertBreak(10);

            Word.Table tb2;
            tb2 = wdDoc.Tables.Add(wdApp.Selection.Range, 2, 4);

            tb2.Columns[1].Width = 40;
            tb2.Columns[2].Width = 180;
            tb2.Columns[3].Width = 180;

            tb2.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wdApp.Selection.Range.Font.Name            = "Times New Roman";
            wdApp.Selection.Range.Font.Size            = 10;
            wdApp.Selection.Cells.VerticalAlignment    = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 0;

            tb2.Rows[1].Select();
            tb2.Cell(1, 2).Range.Text = "Директор колледжа";
            tb2.Cell(1, 4).Range.Text = " ";

            tb2.Rows[2].Select();
            tb2.Cell(2, 2).Range.Text = " ";
            tb2.Cell(2, 3).Range.Text = " ";

            //нумерация страниц
            Word.Window activeWindow = wdDoc.Application.ActiveWindow;
            object      currentPage  = Word.WdFieldType.wdFieldPage;
            object      totalPages   = Word.WdFieldType.wdFieldNumPages;

            //переход к редактированию футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
            activeWindow.ActivePane.Selection.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            //напечатает номер страницы в формате X стр. из Y
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref currentPage, ref wdMiss, ref wdMiss);
            activeWindow.Selection.TypeText(" стр. из ");
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref totalPages, ref wdMiss, ref wdMiss);
            //выход из футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

            wdApp.Visible = true; //показать документ пользователю
        }
Пример #15
0
        /// <summary>
        /// In HS nhân sự
        /// </summary>
        /// <param name="hoSoData">DataSet phải chứa các bảng sau:
        /// + VW_IN_HSNS_THONGTINCHINH : View chứa thông tin chính của nhân sự
        ///
        /// </param>
        /// <returns></returns>
        public bool InHoSoNhanSu(DataSet hoSoData)
        {
            bool        result  = false;
            object      missing = System.Reflection.Missing.Value;
            Application wordApp = new Application();
            Document    aDoc    = null;

            try
            {
                string folder = Constants.FolderTempate;
                //if (Function.GetDefVal(Constants.MDFolderTemplateCer) != "")
                //    folder = Function.GetDefVal(Constants.MDFolderTemplateCer);

                // object fileName = _docTemplate;

                //string fileName = "C:\\RICONS\\TEMPLATE\\" + DateTime.Now.ToString("ddMMyyyyHHmmss") + "Denghimuasamthietbi.xls";

                object saveAs = folder + DateTime.Now.ToString("ddMMyyyyHHmmss") + "_" + "print.doc";

                if (!Directory.Exists(folder + "TMP"))
                {
                    Directory.CreateDirectory(folder + "TMP");
                }

                object readOnly  = false;
                object isVisible = false;

                //Set Word to be not visible.
                wordApp.Visible = false;

                //Open the word document
                object fileNameTemp = _docTemplate;
                aDoc = wordApp.Documents.Open(ref fileNameTemp, ref missing,
                                              ref readOnly, ref missing, ref missing, ref missing,
                                              ref missing, ref missing, ref missing, ref missing,
                                              ref missing, ref isVisible, ref missing, ref missing,
                                              ref missing, ref missing);

                // Activate the document
                aDoc.Activate();

                DataRow nhanVienRow = hoSoData.Tables["VW_IN_HSNS_THONGTINCHINH"].Rows[0];

                // Param replace shape
                Hashtable param = _baseWord.GetTextBoxParams(nhanVienRow); // Chắc chắn rằng HS có dữ liệu

                /* Tạm thời lấy giá trị dòng đầu tiên của trình độ tin học và trình độ ngoại ngữ để fill vào trường tin học & ngoại ngũ trong HS */
                DataTable nvTinHoc = hoSoData.Tables["hrm_nhanvien_tinhoc"];
                if (nvTinHoc.Rows.Count > 0)
                {
                    param["txttinhoc"] = nvTinHoc.Rows[0]["bangcap"];
                }

                DataTable nvNgoaiNgu = hoSoData.Tables["hrm_nhanvien_ngoaingu"];
                if (nvNgoaiNgu.Rows.Count > 0)
                {
                    param["txtngoaingu"] = nvNgoaiNgu.Rows[0]["ngoaingu_ten"];
                }

                //Replace shape
                _baseWord.FindAndReplaceShapeTextBox(wordApp, param);

                // Nếu tồn tại hình ảnh thì xử lý insert hình ảnh
                if (nhanVienRow["anhemb"] != DBNull.Value)
                {
                    string fileImageTemp = Path.GetDirectoryName(_docTemplate) + "\\" + Guid.NewGuid() + ".JPG";

                    //Utilities ult = new DT.CommonLib.Utilities();
                    //System.Drawing.Image image = ult.ConvertBinaryToImage((byte[])nhanVienRow["anhemb"]);
                    //image.Save(fileImageTemp, ImageFormat.Jpeg);

                    // Insert image to doc
                    InlineShape inlineShape = aDoc.Tables[1].Cell(1, 1)
                                              .Range.InlineShapes.AddPicture(fileImageTemp, ref missing, ref missing, ref missing);
                    inlineShape.Width  = 100;
                    inlineShape.Height = 120;

                    //// Xóa hình tạm:
                    FileInfo f = new FileInfo(fileImageTemp);
                    f.Delete();
                }

                /* Fill quá trình công tác */
                wordns.Table docQtct           = aDoc.Tables[6];
                DataTable    nvQuaTrinhCongTac = hoSoData.Tables["HRM_NHANVIEN_QTCONGTAC"];

                int qtctRowIndex = 2;
                foreach (DataRow row in nvQuaTrinhCongTac.Rows)
                {
                    string tuNgay   = row["ngaybatdau"].ToString();
                    string denNgay  = row["ngayketthuc"].ToString();
                    string thoiGian = tuNgay.Length > 7 ? tuNgay.Substring(tuNgay.Length - 7) : tuNgay;
                    thoiGian  = thoiGian + " - ";
                    thoiGian += denNgay.Length > 7 ? denNgay.Substring(denNgay.Length - 7) : denNgay;
                    wordns.Row docRow = docQtct.Rows[qtctRowIndex];
                    docRow.Cells[1].Range.Text = thoiGian;
                    docRow.Cells[2].Range.Text = row["congviec"].ToString();
                    qtctRowIndex += 1;
                }

                /* Fill quan hệ gia đình */
                DataTable nvQhgd = hoSoData.Tables["HRM_NHANVIEN_QUANHEGD"];
                if (nvQhgd.Rows.Count > 0)
                {
                    int          qhBanThanRowIndex     = 2;
                    int          qhVoHoacChongRowIndex = 2;
                    wordns.Table docBanThan            = aDoc.Tables[7];
                    wordns.Table docBenVoHoacChong     = aDoc.Tables[8];
                    bool         isNam   = nhanVienRow["gioitinh"].Equals("Nam");
                    string       banThan = isNam ? "0" : "1";
                    foreach (DataRow row in nvQhgd.Rows)
                    {
                        string quanHe  = row["quanhe_ten"].ToString();
                        string hoTen   = row["hoten"].ToString();
                        string namSinh = row["ngaysinh"].ToString();
                        namSinh = (namSinh.Length <= 4) ? namSinh : namSinh.Substring(0, 4); // Chỉ lấy năm sinh
                        string noiDung = string.Format("{0}, {1}", row["hkthuongtru"], row["nghenghiep"]);

                        if (row["benvo"].Equals(banThan)) /* Fill DL vào bảng quan hệ gia đình - Bản thân */
                        {
                            wordns.Row docBanThanRow = docBanThan.Rows[qhBanThanRowIndex];
                            docBanThanRow.Cells[1].Range.Text = quanHe;
                            docBanThanRow.Cells[2].Range.Text = hoTen;
                            docBanThanRow.Cells[3].Range.Text = namSinh;
                            docBanThanRow.Cells[4].Range.Text = noiDung;
                            qhBanThanRowIndex += 1;
                        }
                        else /* Fill DL vào bảng quan hệ gia đình - Bên vợ | chồng */
                        {
                            wordns.Row docVoHoacChongRow = docBenVoHoacChong.Rows[qhVoHoacChongRowIndex];
                            docVoHoacChongRow.Cells[1].Range.Text = quanHe;
                            docVoHoacChongRow.Cells[2].Range.Text = hoTen;
                            docVoHoacChongRow.Cells[3].Range.Text = namSinh;
                            docVoHoacChongRow.Cells[4].Range.Text = noiDung;
                            qhVoHoacChongRowIndex += 1;
                        }
                    }
                }

                aDoc.SaveAs(ref saveAs, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing);

                aDoc.Close(ref missing, ref missing, ref missing);

                //Open the document as the correct file name
                wordApp.Documents.Open(ref saveAs, ref missing,
                                       ref readOnly, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing,
                                       ref missing, ref isVisible, ref missing, ref missing,
                                       ref missing, ref missing);

                wordApp.Visible = true;

                result = true;
            }
            catch (Exception ex)
            {
                aDoc = null;
                wordApp.Documents.Close();
            }
            return(result);
        }
Пример #16
0
        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            var t = e.Argument as Tuple <bool, bool, string, bool>;

            if (t.Item3 == "")
            {
                MessageBox.Show("Группа не задана!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //здесь формирование ворд-документа для медчасти
            string select = @"SELECT     Student.name, Student.birth, city.city, district.district, Student.country, Student.street, Student.house, Student.flat, Student.phone
                                                FROM         Student INNER JOIN
                                                city ON Student.id_city = city.id INNER JOIN
                                                district ON Student.id_district = district.id INNER JOIN
                                                [Group] ON Student.idGroup = [Group].id 
                                                WHERE idGroup = " + ConvertGroupNameToIdGroup(t.Item3) +
                            @" AND (prikazNumKval = '') AND (prikazNumOut = '') 
                                                ORDER BY name";
            DataSet ds1 = new DataSet();

            try
            {
                ds1 = Util.FillTable("Student", select);
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }

            if (ds1.Tables[0].Rows.Count == 0)
            {
                MessageBox.Show("С указанными данными никого нет!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Word.Application wdApp  = new Word.Application();
            Word.Document    wdDoc  = new Word.Document();
            Object           wdMiss = System.Reflection.Missing.Value;

            wdDoc = wdApp.Documents.Add(ref wdMiss, ref wdMiss, ref wdMiss, ref wdMiss);
            //wdApp.Visible = true; //сначала формируется документ, показывать потом
            wdDoc.PageSetup.Orientation  = Word.WdOrientation.wdOrientLandscape;
            wdDoc.PageSetup.LeftMargin   = 40;
            wdDoc.PageSetup.RightMargin  = 25;
            wdDoc.PageSetup.TopMargin    = 20;
            wdDoc.PageSetup.BottomMargin = 20;
            Word.Table tb;
            Word.Range _range;

            int columnsCount = 7;

            tb = wdDoc.Tables.Add(wdApp.Selection.Range, ds1.Tables[0].Rows.Count + 3, columnsCount);
            tb.Columns[1].Width = 30;
            tb.Rows[1].Height   = 25;
            tb.Columns[2].Width = 210;
            tb.Rows[2].Height   = 40;
            tb.Columns[3].Width = 60;
            tb.Rows[3].Height   = 40;
            tb.Columns[4].Width = 150;
            tb.Columns[5].Width = 60;
            tb.Columns[6].Width = 60;
            tb.Columns[7].Width = 210;

            Word.Row  row       = tb.Rows[1];
            Word.Cell firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }
            row       = tb.Rows[2];
            firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }

            tb.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wdApp.Selection.Range.Font.Name            = "Times New Roman";
            wdApp.Selection.Range.Font.Size            = 10;
            wdApp.Selection.Cells.VerticalAlignment    = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 0;

            tb.Cell(1, 1).Select();
            wdApp.Selection.Range.Font.Size = 14;
            wdApp.Selection.Font.Bold       = 1;
            tb.Cell(1, 1).Range.Text        = "Список";
            tb.Rows[2].Select();
            wdApp.Selection.Range.Font.Size = 12;
            wdApp.Selection.Font.Bold       = 1;
            tb.Cell(2, 1).Range.Text        = " студентов группы " + t.Item3;

            tb.Rows[3].Select();
            wdApp.Selection.Font.Bold = 1;
            tb.Cell(3, 1).Range.Text  = "№ п/п";
            tb.Cell(3, 2).Range.Text  = "ФИО";
            tb.Cell(3, 3).Range.Text  = "Дата рождения";
            tb.Cell(3, 4).Range.Text  = "Домашний адрес";
            tb.Cell(3, 5).Range.Text  = "Группа здоров.";
            tb.Cell(3, 6).Range.Text  = "Физк. группа";
            tb.Cell(3, 7).Range.Text  = "Диагноз";


            int rowCount  = 3;
            int rowNumber = 0;

            foreach (DataRow str in ds1.Tables[0].Rows)
            {
                rowCount++;
                rowNumber++;
                tb.Cell(rowCount, 1).Range.Text = rowNumber.ToString() + ".";
                tb.Cell(rowCount, 2).Range.Text = str.ItemArray[0].ToString();
                tb.Cell(rowCount, 3).Range.Text = DateTime.Parse(str.ItemArray[1].ToString()).ToShortDateString();
                tb.Cell(rowCount, 4).Range.Text = str.ItemArray[2].ToString() + "   " + str.ItemArray[3].ToString() + " р-н" + " ул. " + str.ItemArray[5].ToString() + " д. " +
                                                  str.ItemArray[6].ToString() + " кв. " + str.ItemArray[7].ToString();
            }

            _range = wdDoc.Range(tb.Cell(4, 2).Range.Start, tb.Cell(rowCount, 5).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            _range = wdDoc.Range(tb.Cell(3, 1).Range.Start, tb.Cell(rowCount, columnsCount).Range.End);
            _range.Select();

            /* вызов макроса для отображения границ таблицы
             * Sub Сетка()
             * 'Сетка макрос
             * With Selection.Borders(wdBorderTop)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderLeft)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderBottom)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderRight)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderHorizontal)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderVertical)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * End Sub
             */
            try
            {
                wdApp.Run("Сетка");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " Сетка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            Word.Window activeWindow = wdDoc.Application.ActiveWindow;
            object      currentPage  = Word.WdFieldType.wdFieldPage;
            object      totalPages   = Word.WdFieldType.wdFieldNumPages;

            //переход к редактированию футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
            activeWindow.ActivePane.Selection.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            //напечатает номер страницы в формате X стр. из Y
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref currentPage, ref wdMiss, ref wdMiss);
            activeWindow.Selection.TypeText(" стр. из ");
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref totalPages, ref wdMiss, ref wdMiss);
            //выход из футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

            wdApp.Visible = true; //показать документ пользователю
        }
Пример #17
0
        private void button1_Click(object sender, EventArgs e)
        {
            Word.Document wd = new Word.Document();
            wd.Activate();
            Object start = Type.Missing;
            Object end   = Type.Missing;

            wd.Content.Font.Size = 12;
            wd.Content.Font.Name = "Times New Roman";
            wd.Content.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            Word.Range rng = wd.Range(ref start, ref end);

            Word.Paragraph wordparagraph = wd.Paragraphs.Add();
            wordparagraph.Range.Text = "Государственное учреждение образования \"Институт бизнеса и менеджмента технологий\" Белорусского государственного университета";
            wordparagraph.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text      = "Карточка №1";
            wordparagraph.Range.Font.Size = 14;
            wordparagraph.Range.Bold      = 1;
            wordparagraph.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text      = "(учета проведенных занятий)";
            wordparagraph.Range.Font.Size = 14;
            wordparagraph.Range.Bold      = 1;
            wordparagraph.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text      = "Преподаватель\t" + lecturerName;
            wordparagraph.Range.Font.Size = 12;
            wordparagraph.Range.Bold      = 0;
            wordparagraph.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Факультет бизнеса";
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Специальность\t" + speciality;
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Курс\t\t" + courseNum + "\t\tГруппа\t\t" + n;
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Учебный год\t\t" + schoolYear + "\t\tСеместр\t\t" + semester.ToString();
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Учебная дисциплина\t" + subject;
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Количество часов по плану";
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Форма занятий";
            wordparagraph.Range.InsertParagraphAfter();

            rng.SetRange(rng.End, rng.End);
            Object defaultTableBehavior = Type.Missing;
            Object autoFitBehavior      = Type.Missing;

            Word.Table tbl = wd.Tables.Add(rng, 1, 7, ref defaultTableBehavior, ref autoFitBehavior);
            SetHeadings(tbl.Cell(1, 1), "№ п/п");
            SetHeadings(tbl.Cell(1, 2), "Тема");
            SetHeadings(tbl.Cell(1, 3), "Тип");
            SetHeadings(tbl.Cell(1, 4), "Дата");
            SetHeadings(tbl.Cell(1, 5), "Время");
            SetHeadings(tbl.Cell(1, 6), "Кол. часов");
            SetHeadings(tbl.Cell(1, 7), "Подпись");
            int i;
            int innerCount = 1;

            for (i = 0; i < lecturerData.Rows.Count; i++)
            {
                string   s   = lecturerData.Rows[i][3].ToString();
                string[] w   = s.Split('.');
                string   res = w[1];
                if (res == curNumMonth)
                {
                    Word.Row newRow = wd.Tables[1].Rows.Add();
                    newRow.Range.Font.Bold = 0;
                    newRow.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    newRow.Cells[1].Range.Text             = innerCount.ToString();
                    tbl.Columns[1].SetWidth(27, Word.WdRulerStyle.wdAdjustSameWidth);
                    newRow.Cells[2].Range.Text = lecturerData.Rows[i][1].ToString();
                    tbl.Columns[2].SetWidth(170, Word.WdRulerStyle.wdAdjustSameWidth);
                    string typeOfLesson = lecturerData.Rows[i][2].ToString();
                    if (typeOfLesson == "Управляемая самостоятельная работа")
                    {
                        newRow.Cells[3].Range.Text = "УСР";
                    }
                    else if (typeOfLesson == "Лабораторная работа")
                    {
                        newRow.Cells[3].Range.Text = "Лаб";
                    }
                    else
                    {
                        newRow.Cells[3].Range.Text = lecturerData.Rows[i][2].ToString();
                    }
                    tbl.Columns[3].SetWidth(60, Word.WdRulerStyle.wdAdjustSameWidth);
                    newRow.Cells[4].Range.Text = lecturerData.Rows[i][3].ToString();
                    tbl.Columns[4].SetWidth(65, Word.WdRulerStyle.wdAdjustSameWidth);
                    newRow.Cells[5].Range.Text = lecturerData.Rows[i][4].ToString();
                    tbl.Columns[5].SetWidth(44, Word.WdRulerStyle.wdAdjustSameWidth);
                    newRow.Cells[6].Range.Text = lecturerData.Rows[i][5].ToString();
                    tbl.Columns[6].SetWidth(40, Word.WdRulerStyle.wdAdjustSameWidth);
                    newRow.Cells[7].Range.Text = lecturerData.Rows[i][6].ToString();
                    tbl.Columns[7].SetWidth(60, Word.WdRulerStyle.wdAdjustSameWidth);
                    innerCount++;
                }
            }
            //i++;
            //wd.Tables[1].Rows.Add();
            //tbl.Rows[i].Cells[0].Merge(tbl.Rows[i].Cells[2]);
        }
Пример #18
0
        /// <summary>
        /// Load quotation controls from xml file data
        /// </summary>
        /// <returns>Successfully loaded Word document</returns>
        public bool LoadQuotation()
        {
            try
            {
                xsTaskCode xmlTask = new xsTaskCode();
                xmlTask.ReadXml(Schema.TaskSingleXmlFileName);
                xsTaskCode.TaskRow taskRow = (xsTaskCode.TaskRow)xmlTask.Task.Rows[0];

                #region header
                WriteControl("ContactName", taskRow.ContactName);
                WriteControl("AccountCode", taskRow.AccountCode);
                WriteControl("AccountName", taskRow.AccountName);
                WriteControl("InvoiceAddress", taskRow.IsInvoiceAddressNull() ? string.Empty : taskRow.InvoiceAddress);
                WriteControl("NickName", taskRow.IsNickNameNull() ? string.Empty : taskRow.NickName);
                WriteControl("TaskCode", taskRow.TaskCode);
                WriteControl("TaskTitle", taskRow.IsTaskTitleNull() ? string.Empty : taskRow.TaskTitle);
                WriteControl("SecondReference", taskRow.IsSecondReferenceNull() ? string.Empty : taskRow.SecondReference);
                WriteControl("TaskNotes", taskRow.IsTaskNotesNull() ? string.Empty : taskRow.TaskNotes);
                WriteControl("UserName", taskRow.UserName);
                WriteControl("CompanyName", taskRow.CompanyName);
                #endregion

                #region Attributes
                Word.Table attributeTable = null;
                Word.Row   attributeRow   = null;
                object     attribObj      = null;
                int[]      idxAttrib      = new int[] { 1, 2 };

                foreach (Word.Table table in document.Tables)
                {
                    foreach (Word.Row row in table.Rows)
                    {
                        foreach (Word.Cell cell in row.Range.Cells)
                        {
                            foreach (Word.ContentControl ctl in cell.Range.ContentControls)
                            {
                                switch (ctl.Tag)
                                {
                                case "a1":
                                    attributeTable = table;
                                    attribObj      = (object)row;
                                    attributeRow   = row;
                                    idxAttrib[0]   = cell.ColumnIndex;
                                    break;

                                case "a2":
                                    idxAttrib[1] = cell.ColumnIndex;
                                    break;
                                }
                            }
                        }
                        if (attributeRow != null)
                        {
                            break;
                        }
                    }
                    if (attributeRow != null)
                    {
                        break;
                    }
                }

                if (attributeRow != null)
                {
                    var attributes = from tb in xmlTask.Attributes
                                     select tb;

                    foreach (xsTaskCode.AttributesRow row in attributes)
                    {
                        if (((AttributeType)row.AttributeTypeCode == AttributeType.Order) ||
                            ((AttributeType)row.AttributeTypeCode == AttributeType.Quote && (TaskStatus)taskRow.TaskStatusCode == TaskStatus.Pending))
                        {
                            Word.Row newRow = attributeTable.Rows.Add(ref attribObj);
                            newRow.Cells[idxAttrib[0]].Range.Text = row.Attribute;
                            newRow.Cells[idxAttrib[1]].Range.Text = row.AttributeDescription;
                        }
                    }

                    attributeRow.Delete();
                }
                #endregion

                #region quote
                Word.Table quoteTable = null;
                Word.Row   quoteRow   = null;
                object     quoteObj   = null;
                int[]      idxQuote   = new int[] { 1, 2, 3, 4, 5, 6 };

                foreach (Word.Table table in document.Tables)
                {
                    foreach (Word.Row row in table.Rows)
                    {
                        foreach (Word.Cell cell in row.Range.Cells)
                        {
                            foreach (Word.ContentControl ctl in cell.Range.ContentControls)
                            {
                                switch (ctl.Tag)
                                {
                                case "q1":
                                    quoteTable  = table;
                                    quoteObj    = (object)row;
                                    quoteRow    = row;
                                    idxQuote[0] = cell.ColumnIndex;
                                    break;

                                case "q2":
                                    idxQuote[1] = cell.ColumnIndex;
                                    break;

                                case "q3":
                                    idxQuote[2] = cell.ColumnIndex;
                                    break;

                                case "q4":
                                    idxQuote[3] = cell.ColumnIndex;
                                    break;

                                case "q5":
                                    idxQuote[4] = cell.ColumnIndex;
                                    break;

                                case "q6":
                                    idxQuote[5] = cell.ColumnIndex;
                                    break;
                                }
                            }
                        }
                        if (quoteRow != null)
                        {
                            break;
                        }
                    }
                    if (quoteRow != null)
                    {
                        break;
                    }
                }

                if (quoteRow != null)
                {
                    var quote = from tb in xmlTask.QuotedPrices
                                orderby tb.QuoteQuantity
                                select tb;

                    foreach (xsTaskCode.QuotedPricesRow row in quote)
                    {
                        Word.Row newRow = attributeTable.Rows.Add(ref quoteObj);
                        newRow.Cells[idxQuote[0]].Range.Text = row.QuoteQuantity.ToQuantity();
                        newRow.Cells[idxQuote[1]].Range.Text = row.QuotePrice.ToCurrency();
                        newRow.Cells[idxQuote[2]].Range.Text = row.RunOnQuantity.ToQuantity();
                        newRow.Cells[idxQuote[3]].Range.Text = row.RunOnPrice.ToCurrency();
                        newRow.Cells[idxQuote[4]].Range.Text = row.RunBackQuantity.ToQuantity();
                        newRow.Cells[idxQuote[5]].Range.Text = row.RunBackPrice.ToCurrency();
                    }

                    quoteRow.Delete();
                }

                #endregion

                return(true);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, $"{err.Source}.{err.TargetSite.Name}", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
        }
Пример #19
0
        /// <summary>
        /// Generate register of systems document using existing file.
        /// </summary>
        /// <param name="tv"></param>
        /// <param name="clientFolder"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public ResponseStatus RegisterOfSytemDocuments2(TreeView tv, string clientFolder, string fileName, string processName, string userID)
        {
            uioutput.AddOutputMessage("Starting Register of Systems Documents generation...", processName, userID);
            uioutput.AddOutputMessage(clientFolder, processName, userID);
            uioutput.AddOutputMessage(fileName, processName, userID);

            ResponseStatus ret = new ResponseStatus();

            object oMissing       = System.Reflection.Missing.Value;
            object vkMissing      = System.Reflection.Missing.Value;
            object vkReadOnly     = false;
            object vkVisiblefalse = false;
            object vkFalse        = false;

            var pastPlannedActivities = string.Empty;

            //Start Word and open the document.
            //WordNet._Application oApplication = new Application { Visible = false };

            // string clientDestinationFileLocation = document.clientDocument.Location.Trim();
            string clientDestinationFileLocation = clientFolder;

            //string clientDestinationFileLocationName = Utils.getFilePathName(
            //    clientDestinationFileLocation, document.clientDocument.FileName.Trim() );

            string clientDestinationFileLocationName = Utils.getFilePathName(clientDestinationFileLocation, fileName.Trim());

            object destinationFileName = clientDestinationFileLocationName;

            if (!File.Exists(clientDestinationFileLocationName))
            {
                uioutput.AddOutputMessage("File doesn't exist " + destinationFileName, processName: processName, userID: userID);
                uioutput.AddErrorMessage("File doesn't exist " + destinationFileName, processName: processName, userID: userID);

                var responseerror = new ResponseStatus(MessageType.Error);

                responseerror.Message = "File doesn't exist " + destinationFileName;
                return(responseerror);
            }

            WordNet._Document oDoc;
            try
            {
                uioutput.AddOutputMessage("Opening document in Word... " + destinationFileName, processName: processName, userID: userID);

                oDoc = oApplication.Documents.Open(
                    ref destinationFileName, ref vkMissing, ref vkFalse,
                    ref vkMissing, ref vkMissing, ref vkMissing,
                    ref vkMissing, ref vkMissing, ref vkMissing,
                    ref vkMissing, ref vkMissing, ref vkVisiblefalse);
            }
            catch (Exception ex)
            {
                var responseerror = new ResponseStatus(MessageType.Error);

                responseerror.ReturnCode = -1;
                responseerror.ReasonCode = 1000;
                responseerror.Message    = "Error copying file.";
                responseerror.Contents   = ex;
                return(responseerror);
            }


            if (oDoc.ReadOnly)
            {
                if (uioutput != null)
                {
                    uioutput.AddOutputMessage("(Word) File is Read-only contact support:  " + destinationFileName, processName, userID);
                }
                oDoc.Close();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);

                var responseerror = new ResponseStatus(MessageType.Error);
                responseerror.Message = "(Word) File is Read-only contact support:  " + destinationFileName;
                return(responseerror);
            }

            try
            {
                if (uioutput != null)
                {
                    uioutput.AddOutputMessage("Saving document in Word... " + destinationFileName, processName, userID);
                }
                oDoc.Save();
            }
            catch (Exception ex)
            {
                if (uioutput != null)
                {
                    uioutput.AddOutputMessage("Error saving file " + clientDestinationFileLocationName, processName, userID);
                }

                var responseerror = new ResponseStatus(MessageType.Error);
                responseerror.Message = "Error saving file " + clientDestinationFileLocationName;
                return(responseerror);
            }

            string msg = ">>> Opening file... " + destinationFileName;

            if (uioutput != null)
            {
                uioutput.AddOutputMessage(msg, processName, userID);
            }

            PrintToWord(oDoc, " ", 8, 1);

            WordNet.Range wrdRng;
            WordNet.Table oTable;

            wrdRng = oDoc.Bookmarks.get_Item(oEndOfDoc).Range;
            int rowCount = 30;


            // Get number of rows for a client document, client document set
            //
            // var cds = new BUSClientDocumentSet( Utils.ClientID, Utils.ClientSetID XXXXXXXXXXXXXXX );
            var cds = new BUSClientDocumentSet(clientID, clientDocSetID);

            rowCount = cds.DocumentCount;

            if (rowCount < 1)
            {
                return(new ResponseStatus(MessageType.Error));
            }

            oTable = oDoc.Tables.Add(wrdRng, rowCount, 8, ref vkFalse, ref vkFalse);
            oTable.Borders.OutsideColor     = WordNet.WdColor.wdColorBlack;
            oTable.Borders.InsideLineStyle  = WordNet.WdLineStyle.wdLineStyleDouble;
            oTable.Borders.OutsideColor     = WordNet.WdColor.wdColorBlueGray;
            oTable.Borders.OutsideLineStyle = WordNet.WdLineStyle.wdLineStyleEmboss3D;

            oTable.Rows [1].HeadingFormat = -1;

            WordNet.Row headingRow = oTable.Rows [1];

            ApplyHeadingStyle(headingRow.Cells [1], 200);
            headingRow.Cells [1].Range.Text = "Directory";

            ApplyHeadingStyle(headingRow.Cells [2], 60);
            headingRow.Cells [2].Range.Text = "Sub Directory";

            ApplyHeadingStyle(headingRow.Cells [3], 80);
            headingRow.Cells [3].Range.Text = "Document Number";

            ApplyHeadingStyle(headingRow.Cells [4], 30);
            headingRow.Cells [4].Range.Text = "Sml";
            ApplyHeadingStyle(headingRow.Cells [5], 40);
            headingRow.Cells [5].Range.Text = "Med";
            ApplyHeadingStyle(headingRow.Cells [6], 30);
            headingRow.Cells [6].Range.Text = "Lrg";

            ApplyHeadingStyle(headingRow.Cells [7], 50);
            headingRow.Cells [7].Range.Text = "Version";

            ApplyHeadingStyle(headingRow.Cells [8], 200);
            headingRow.Cells [8].Range.Text = "Document Name";

            int line = 0;

            foreach (var treeNode in tv.Nodes)
            {
                line++;
                WriteLineToRoSD(tv.Nodes [0], oDoc, oTable, prefix: "", parent: "", seqnum: line);
            }

            msg = ">>> End ";
            if (uioutput != null)
            {
                uioutput.AddOutputMessage(msg, processName, userID);
            }

            PrintToWord(oDoc, " ", 12, 1);

            try
            {
                oDoc.Save();
            }
            catch (Exception ex)
            {
                if (uioutput != null)
                {
                    uioutput.AddOutputMessage("Error saving file again... " + clientDestinationFileLocationName, processName, userID);
                }

                var responseerror = new ResponseStatus(MessageType.Error);
                responseerror.Message = "Error saving file again... " + clientDestinationFileLocationName;
                return(responseerror);
            }

            oDoc.Close();

            ResponseStatus goodresponse = new ResponseStatus(MessageType.Informational);

            goodresponse.Message = "Document SRG-01 generated successfully.";
            return(goodresponse);
        }
Пример #20
0
        /// <summary>
        /// Collect a workweeks worrth of data from the selected calendars
        /// and then open the template and replace each of the days fields
        /// </summary>
        private void exportDays(int PintStart = 1)
        {
            try
            {
                Common.LoadProgress(MobjAppointments.Count, "Preparing...");

                Word.Document LobjDoc = openDocument();
                updateHeader(LobjDoc);
                int LintCount = PintStart;
                foreach (DailyAppointments LobjDay in MobjAppointments)
                {
                    Common.IncrementProgress("Exporting day " + LobjDay.Date.ToLongDateString() + "...");
                    int LintNumber = LobjDay.Appointments.Count;

                    // update the day number - usually for monthly
                    LobjDoc.FindReplace("<<day" + LintCount.ToString() + ">>",
                                        (LintCount - PintStart + 1).GetOrdinal());

                    foreach (ExtendedAppointment LobjAppt in LobjDay.Appointments)
                    {
                        // Do we only care about shared meetings?
                        // is this a shared meetings between two or more of the
                        // recipients in this export?
                        if (LobjAppt.Recipients.Count == 1 &&
                            MobjSettings.ExportWhat == AddinSettings.ExportType.Shared)
                        {
                            continue; // skip because we only want to see shared meetings
                        }

                        Word.Range LobjTimeRange = LobjDoc.FindReplace(
                            "<<time" + LintCount.ToString() + ">>",
                            LobjAppt.Start.Hour.ToString("00") + ":" +
                            LobjAppt.Start.Minute.ToString("00") + " - " +
                            LobjAppt.End.Hour.ToString("00") + ":" +
                            LobjAppt.End.Minute.ToString("00"));
                        Word.Range LobjTitleRange = null;

                        string LstrSymbols = " (" + LobjAppt.Recipients.ToStringOfSymbols() + ")";
                        string LstrData    = LobjAppt.Subject;

                        // see if we need to obfuscate the meeting information
                        if (MobjSettings.DisplayTimeOnly)
                        {
                            // we only going to show a generic -- Meeting -- or
                            //                                 -- Appointment --
                            if (LobjAppt.IsMeeting)
                            {
                                LstrData = " -- MEETING --";
                            }
                            else
                            {
                                LstrData = " -- APPOINTMENT --";
                            }
                        }

                        // is there is only one recipient, we do not
                        // need symbols so lets remove them...
                        if (MobjSettings.Recipients.Count == 1)
                        {
                            // we do not need symbols
                            LstrSymbols = "";
                        }

                        // if there is no location - OR
                        // we want to hide the lcoations
                        if (string.IsNullOrEmpty(LobjAppt.Location) ||
                            MobjSettings.ShowLocation == false)
                        {
                            // export without a location
                            LobjTitleRange = LobjDoc.FindReplace(
                                "<<title" + LintCount.ToString() + ">>",
                                LstrData + LstrSymbols);
                        }
                        else
                        {
                            // otherwise export with the location
                            LobjTitleRange = LobjDoc.FindReplace(
                                "<<title" + LintCount.ToString() + ">>",
                                LstrData + LstrSymbols +
                                "[" + LobjAppt.Location + "]");
                        }

                        // add emphasis
                        if (LobjAppt.Recurring && MobjSettings.EmphasizeRecurring)
                        {
                            LobjTitleRange.Font.Italic = 1;
                            LobjTimeRange.Font.Italic  = 1;
                        }

                        LintNumber--;
                        // if there are more appointments for the same day
                        // we want to add a new row to the inner table for that day
                        if (LintNumber > 0)
                        {
                            if (LobjTimeRange.Tables.Count > 0)
                            {
                                Word.Row LobjRow = LobjTimeRange.Rows.Add();
                                // add our find items
                                LobjRow.Cells[1].Range.Text = "<<time" + LintCount.ToString() + ">>";
                                LobjRow.Cells[2].Range.Text = "<<title" + LintCount.ToString() + ">>";
                            }
                            else
                            {
                                LobjTimeRange.InsertAfter("<<time" + LintCount.ToString() + ">>");
                                LobjTitleRange.InsertAfter("<<title" + LintCount.ToString() + ">>");
                            }
                        }
                    }
                    // increment last
                    LintCount++;
                }

                // cleanup - we remove any boilerplate items that were not used
                for (int LintX = 1; LintX <= 42; LintX++)
                {
                    LobjDoc.FindReplace("<<time" + LintX.ToString() + ">>", "");
                    LobjDoc.FindReplace("<<title" + LintX.ToString() + ">>", "");
                    LobjDoc.FindReplace("<<day" + LintX.ToString() + ">>", "");
                }

                // now delete empty tables - the cleans up unused days
                foreach (Word.Table LobjTable in LobjDoc.Tables)
                {
                    LobjTable.DeleteEmpty();
                }

                colorCode(LobjDoc); // done
                LobjDoc.Application.Visible = true;
                Common.CloseProgress();
            }
            catch (Exception PobjEx)
            {
                throw new Exception("Failed exporting the week. " + PobjEx.Message);
            }
        }
Пример #21
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var t = e.Argument as Tuple <string, bool>;

            if (String.IsNullOrWhiteSpace(t.Item1)) //вставить проверку, что указаны годы
            {
                MessageBox.Show("Не указаны годы рождения!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string select = @"SELECT Student.name";

            if (t.Item2 == false)
            {
                select += ", Student.birth";
            }
            select += @" FROM Student INNER JOIN
                             [Group] ON Student.idGroup = [Group].id 
                        WHERE idGroup = " + ConvertGroupNameToIdGroup(t.Item1) + @" AND (prikazNumKval = '') AND (prikazNumOut = '') 
                        ORDER BY name";

            DataSet ds1 = new DataSet();

            try
            {
                ds1 = Util.FillTable("Student", select);
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }

            if (ds1.Tables[0].Rows.Count == 0)
            {
                MessageBox.Show("С указанными данными никого нет!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Word.Application wdApp  = new Word.Application();
            Word.Document    wdDoc  = new Word.Document();
            Object           wdMiss = System.Reflection.Missing.Value;

            wdDoc = wdApp.Documents.Add(ref wdMiss, ref wdMiss, ref wdMiss, ref wdMiss);
            //wdApp.Visible = true; //сначала формируется документ, показывать потом
            wdDoc.PageSetup.LeftMargin   = 40;
            wdDoc.PageSetup.RightMargin  = 25;
            wdDoc.PageSetup.TopMargin    = 50;
            wdDoc.PageSetup.BottomMargin = 20;
            Word.Table tb;
            Word.Range _range;

            int columnsCount = 0;

            if (t.Item2 == true)
            {
                columnsCount = 3;
            }
            else
            {
                columnsCount = 4;
            }

            tb = wdDoc.Tables.Add(wdApp.Selection.Range, ds1.Tables[0].Rows.Count + 2, columnsCount);
            tb.Columns[1].Width = 40;
            tb.Rows[1].Height   = 30;
            tb.Columns[2].Width = 300;
            tb.Rows[2].Height   = 20;
            if (t.Item2 == true)
            {
                tb.Columns[3].Width = 186;
            }
            else
            {
                tb.Columns[3].Width = 86;
                tb.Columns[4].Width = 100;
            }

            Word.Row  row       = tb.Rows[1];
            Word.Cell firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }

            tb.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wdApp.Selection.Range.Font.Name            = "Times New Roman";
            wdApp.Selection.Range.Font.Size            = 10;
            wdApp.Selection.Cells.VerticalAlignment    = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 0;

            tb.Cell(1, 1).Select();
            wdApp.Selection.Range.Font.Size = 14;
            wdApp.Selection.Font.Bold       = 1;
            tb.Cell(1, 1).Range.Text        = "Группа " + t.Item1;

            tb.Rows[2].Select();
            wdApp.Selection.Font.Bold = 1;
            tb.Cell(2, 1).Range.Text  = "№ п/п";
            tb.Cell(2, 2).Range.Text  = "Ф.И.О.";
            if (t.Item2 == true)
            {
                tb.Cell(2, 3).Range.Text = "Примечание";
            }
            else
            {
                tb.Cell(2, 3).Range.Text = "Дата рожд.";
                tb.Cell(2, 4).Range.Text = "Примечание";
            }

            int rowCount  = 2;
            int rowNumber = 0;

            foreach (DataRow str in ds1.Tables[0].Rows)
            {
                rowCount++;
                rowNumber++;
                tb.Cell(rowCount, 1).Range.Text = rowNumber.ToString() + ".";
                tb.Cell(rowCount, 2).Range.Text = str.ItemArray[0].ToString();
                if (t.Item2 == false)
                {
                    try
                    {
                        tb.Cell(rowCount, 3).Range.Text = DateTime.Parse(str.ItemArray[1].ToString()).ToShortDateString();
                    }
                    catch
                    {
                        tb.Cell(rowCount, 3).Range.Text = str.ItemArray[1].ToString();
                    }
                }
            }

            _range = wdDoc.Range(tb.Cell(3, 2).Range.Start, tb.Cell(rowCount, 2).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            _range = wdDoc.Range(tb.Cell(3, columnsCount).Range.Start, tb.Cell(rowCount, columnsCount).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;


            _range = wdDoc.Range(tb.Cell(2, 1).Range.Start, tb.Cell(rowCount, columnsCount).Range.End);
            _range.Select();

            /* вызов макроса для отображения границ таблицы
             * Sub Сетка()
             * 'Сетка макрос
             * With Selection.Borders(wdBorderTop)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderLeft)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderBottom)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderRight)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderHorizontal)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderVertical)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * End Sub
             */
            try
            {
                wdApp.Run("Сетка");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " Сетка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            //нумерация страниц
            Word.Window activeWindow = wdDoc.Application.ActiveWindow;
            object      currentPage  = Word.WdFieldType.wdFieldPage;
            object      totalPages   = Word.WdFieldType.wdFieldNumPages;

            //переход к редактированию футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
            activeWindow.ActivePane.Selection.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            //напечатает номер страницы в формате X стр. из Y
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref currentPage, ref wdMiss, ref wdMiss);
            activeWindow.Selection.TypeText(" стр. из ");
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref totalPages, ref wdMiss, ref wdMiss);
            //выход из футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

            wdApp.Visible = true; //показать документ пользователю
        }
Пример #22
0
        private void btnLoadForm_Click(object sender, EventArgs e)
        {
            // ===================== Populate Date Generated ==============================
            Word.ContentControl ccDateGenerated = GetContentControl("txtDateGenerated");
            ccDateGenerated.Range.Text = DateTime.Now.ToString("MM/dd/yyyy");

            String Stage = "Page Load";

            WebCollection childWebs = null;

            String txtURL = String.Empty;

            Word.ContentControl ccURL = GetContentControl("txtURL");

            // Clear errors
            SetContentControl("txtSmartArtError", "");
            SetContentControl("txtURLError", "");

            if (ccURL != null)
            {
                Stage = "Load Action Pane";
                // http://oigportal.hhsoig.gov/sites/OAS/AATS/TMSIS
                txtURL = ccURL.Range.Text;

                txtURL = txtURL.Replace("SitePages/Home.aspx", "");

                txtURL = txtURL.TrimEnd('/');

                actionPane.URL = txtURL;
                actionPane.LoadControl();



                try
                {
                    Stage = "Load Web";
                    ClientContext clientContext = new ClientContext(txtURL);
                    Web           currentWeb    = clientContext.Web;

                    clientContext.Load(currentWeb);
                    clientContext.ExecuteQuery();

                    // Get Web details
                    Guid webId = currentWeb.Id;
                    SetContentControl("txtTitle", currentWeb.Title);
                    SetContentControl("txtCreated", currentWeb.Created.ToString("MM/dd/yyyy"));
                    SetContentControl("txtModified", currentWeb.LastItemModifiedDate.ToString("MM/dd/yyyy"));

                    long webSize = GetWebSize(currentWeb);
                    SetContentControl("txtSize", webSize.ToString("N0"));

                    // Set document properties
                    Microsoft.Office.Core.DocumentProperties properties;
                    properties = (Office.DocumentProperties) this.CustomDocumentProperties;

                    // properties["Title"].Value = currentWeb.Title;

                    #region Smart Art Population
                    // ============ Smart Art =====================================================

                    try
                    {
                        // Set up for diagram
                        Stage = "Modify Smart Art";
                        // for background color of the current web cell in the smartart.
                        const int OrangeCell = unchecked ((int)0xED7D31);

                        Site tempSite = clientContext.Site;
                        clientContext.Load(tempSite);
                        clientContext.ExecuteQuery();

                        string siteUrl = tempSite.Url + "/";                          // http://oigportal.hhsoig.gov/sites/OAS

                        Web tmpRoot = tempSite.RootWeb;
                        clientContext.Load(tmpRoot);
                        clientContext.ExecuteQuery();

                        string rootTitle = tmpRoot.Title;

                        // Get site names by breaking down URL.
                        //  SharePoint 2010 client Web class doesn't have any way to get the parent web.
                        //  example: AATS/TMSIS
                        string   navTree = txtURL.Replace(siteUrl, "");
                        string[] nodes   = navTree.Split('/');

                        // Find the diagram and get a reference to it.
                        Word.InlineShape treeShape = null;

                        foreach (Word.InlineShape tmpShape in this.InlineShapes)
                        {
                            if (tmpShape.Type == Word.WdInlineShapeType.wdInlineShapeSmartArt)
                            {
                                treeShape = tmpShape;
                            }
                        }

                        Office.SmartArt treeArt = treeShape.SmartArt;
                        // treeShape.Height

                        // clear out existing nodes
                        foreach (Office.SmartArtNode tmpNode in treeArt.Nodes)
                        {
                            if (tmpNode != null)
                            {
                                tmpNode.Delete();
                            }
                        }

                        Office.SmartArtNode rootNode = treeArt.Nodes.Add();
                        rootNode.TextFrame2.TextRange.Text = rootTitle;

                        // Nodes from root to current site
                        foreach (string tmpNodeText in nodes)
                        {
                            Office.SmartArtNode tmpChildNode = treeArt.Nodes.Add();
                            tmpChildNode.TextFrame2.TextRange.Text = tmpNodeText;
                        }

                        // Root node - add then node, then set the text.
                        Office.SmartArtNode currentNode = treeArt.Nodes[treeArt.Nodes.Count];
                        currentNode.TextFrame2.TextRange.Text = currentWeb.Title;
                        // set root node color

                        currentNode.Shapes.Fill.ForeColor.RGB = 0xED7D31;                         // OrangeCell;

                        // Child webs for SmartArt
                        childWebs = currentWeb.Webs;
                        clientContext.Load(childWebs);
                        clientContext.ExecuteQuery();

                        foreach (Web tmpWeb in childWebs)
                        {
                            Office.SmartArtNode childNode = currentNode.AddNode(Office.MsoSmartArtNodePosition.msoSmartArtNodeBelow);
                            childNode.TextFrame2.TextRange.Text = tmpWeb.Title;
                        }
                    }
                    catch (Exception ex)
                    {
                        Word.ContentControl smartArtError = GetContentControl("txtSmartArtError");
                        Word.Range          tagRange      = smartArtError.Range;
                        tagRange.Text       = String.Concat("ERROR: ", ex.Message);
                        tagRange.Font.Color = Word.WdColor.wdColorRed;
                    }

                    #endregion

                    #region Build Child Web Table
                    // ============ Child Web Table ===============================================
                    Stage = "Load Child Web Table";

                    Word.Table webTable = GetTable("ChildWebs");

                    if (webTable != null)
                    {
                        foreach (Web tmpWeb in childWebs)
                        {
                            Word.Row newRow = webTable.Rows.Add();

                            newRow.Cells[1].Range.Text = tmpWeb.Title;
                            newRow.Cells[2].Range.Text = tmpWeb.ServerRelativeUrl;
                            // newRow.Cells[3].Range.Text = Owners
                            newRow.Cells[4].Range.Text = tmpWeb.Created.ToString("MM/dd/yyyy");

                            long WebSize = GetWebSize(tmpWeb);
                            newRow.Cells[5].Range.Text = WebSize.ToString("N0");
                        }
                    }
                    #endregion

                    #region Build Child Object Table
                    // ================== Child Object Table =========================================
                    Microsoft.SharePoint.Client.ListCollection webLists = currentWeb.Lists;
                    clientContext.Load(webLists);
                    clientContext.ExecuteQuery();

                    Word.Table objTable = GetTable("tblContentObjects");

                    if (objTable != null)
                    {
                        foreach (List tmpList in webLists)
                        {
                            Word.Row newRow = objTable.Rows.Add();

                            newRow.Cells[1].Range.Text = tmpList.BaseType.ToString();
                            newRow.Cells[2].Range.Text = tmpList.Title;
                            newRow.Cells[3].Range.Text = tmpList.ItemCount.ToString();
                            newRow.Cells[4].Range.Text = tmpList.LastItemModifiedDate.ToString("MM/dd/yyyy");
                        }
                    }
                    #endregion

                    #region Build Permissions Table
                    // =================== Permissions Table ==============================================
                    Stage = "Load Permissions Table";
                    Word.Table permTable = GetTable("tblPermissions");

                    RoleAssignmentCollection roleAssignments = currentWeb.RoleAssignments;
                    clientContext.Load(roleAssignments);
                    clientContext.ExecuteQuery();

                    Stage = "Role Assignments";
                    foreach (RoleAssignment assign in roleAssignments)
                    {
                        clientContext.Load(assign);
                        clientContext.ExecuteQuery();

                        Stage = "Load Role Principal";
                        Principal tmpMember = assign.Member;
                        clientContext.Load(tmpMember);
                        clientContext.ExecuteQuery();

                        Word.Row newRow = permTable.Rows.Add();

                        newRow.Cells[1].Range.Text = assign.Member.Title;
                        newRow.Cells[2].Range.Text = assign.Member.PrincipalType.ToString();
                        newRow.Cells[3].Range.Text = assign.Member.LoginName;

                        Stage = "Role Collection";
                        RoleDefinitionBindingCollection roles = assign.RoleDefinitionBindings;
                        clientContext.Load(roles);
                        clientContext.ExecuteQuery();

                        Stage = "Role Definitions";
                        foreach (RoleDefinition roleDef in roles)
                        {
                            clientContext.Load(roleDef);
                            clientContext.ExecuteQuery();

                            switch (roleDef.Name)
                            {
                            case "Full Control":
                                newRow.Cells[4].Range.Text = "X";
                                break;

                            case "Design":
                                newRow.Cells[5].Range.Text = "X";
                                break;

                            case "Contribute":
                                newRow.Cells[6].Range.Text = "X";
                                break;

                            case "Read":
                                newRow.Cells[7].Range.Text = "X";
                                break;
                            }
                        }
                    }
                    #endregion

                    #region Fill Workflow Table
                    Stage = "Load Workflow Table";

                    Word.Table workflowTable = GetTable("tblWorkflows");

                    WorkflowAssociationCollection workflows = currentWeb.WorkflowAssociations;

                    clientContext.Load(workflows);
                    clientContext.ExecuteQuery();

                    foreach (WorkflowAssociation workflow in workflows)
                    {
                        clientContext.Load(workflow);
                        clientContext.ExecuteQuery();

                        Word.Row newRow = workflowTable.Rows.Add();

                        newRow.Cells[1].Range.Text = workflow.Name;
                    }

                    #endregion
                }
                catch (Exception ex)
                {
                    Word.ContentControl urlError = GetContentControl("txtURLError");
                    Word.Range          rngError = urlError.Range;
                    rngError.Text       = String.Concat("ERROR at stage ", Stage, ": ", ex.Message);
                    rngError.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorRed;
                }
            }
        }
Пример #23
0
        public void Print()
        {
            Word.Application wdApp  = new Word.Application();
            Word.Document    wdDoc  = new Word.Document();
            Object           wdMiss = System.Reflection.Missing.Value;

            wdDoc         = wdApp.Documents.Add(ref wdMiss, ref wdMiss, ref wdMiss, ref wdMiss);
            wdApp.Visible = true; //сначала формируется документ, показывать потом
            wdDoc.PageSetup.LeftMargin   = 40;
            wdDoc.PageSetup.RightMargin  = 25;
            wdDoc.PageSetup.TopMargin    = 20;
            wdDoc.PageSetup.BottomMargin = 20;
            Word.Table tb;
            Word.Range _range;

            int columnsCount = 4;

            tb = wdDoc.Tables.Add(wdApp.Selection.Range, rowColl.Count + 2, columnsCount);
            tb.Columns[1].Width = 40;
            tb.Rows[1].Height   = 30;
            tb.Columns[2].Width = 240;
            tb.Rows[2].Height   = 30;
            tb.Columns[3].Width = 80;
            tb.Rows[3].Height   = 40;
            tb.Columns[4].Width = 180;

            Word.Row  row       = tb.Rows[1];
            Word.Cell firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }
            row       = tb.Rows[2];
            firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }

            tb.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wdApp.Selection.Range.Font.Name            = "Times New Roman";
            wdApp.Selection.Range.Font.Size            = 10;
            wdApp.Selection.Cells.VerticalAlignment    = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 0;

            tb.Cell(1, 1).Select();
            wdApp.Selection.Range.Font.Size = 14;
            wdApp.Selection.Font.Bold       = 1;
            tb.Cell(1, 1).Range.Text        = "Список";
            tb.Rows[2].Select();
            wdApp.Selection.Range.Font.Size = 12;
            wdApp.Selection.Font.Bold       = 1;
            //tb.Cell(2, 1).Range.Text = "студентов, обучающихся на коммерческой основе на " + DateTime.Now.ToShortDateString() + " г.";

            tb.Rows[3].Select();
            wdApp.Selection.Font.Bold = 1;
            tb.Cell(3, 1).Range.Text  = "№ п/п";
            tb.Cell(3, 2).Range.Text  = "ФИО";
            tb.Cell(3, 3).Range.Text  = "Дата рождения";
            tb.Cell(3, 4).Range.Text  = "Примечание";


            int rowCount  = 3;
            int rowNumber = 0;

            foreach (DataGridViewRow str in rowColl)
            {
                rowCount++;
                rowNumber++;
                if (rowNumber == rowColl.Count)
                {
                    break;
                }
                tb.Cell(rowCount, 1).Range.Text = rowNumber.ToString() + ".";
                tb.Cell(rowCount, 2).Range.Text = str.Cells[0].Value.ToString();            //фио
                tb.Cell(rowCount, 3).Range.Text = str.Cells[1].Value.ToString().Remove(11); //дата рождения
                tb.Cell(rowCount, 4).Range.Text = str.Cells[30].Value.ToString();           //примечание
            }

            _range = wdDoc.Range(tb.Cell(4, 2).Range.Start, tb.Cell(rowCount, 2).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 10;
            _range = wdDoc.Range(tb.Cell(4, 4).Range.Start, tb.Cell(rowCount, 4).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 10;
            _range = wdDoc.Range(tb.Cell(3, 1).Range.Start, tb.Cell(rowCount, columnsCount).Range.End);
            _range.Select();

            /* вызов макроса для отображения границ таблицы
             * Sub Сетка()
             * 'Сетка макрос
             * With Selection.Borders(wdBorderTop)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderLeft)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderBottom)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderRight)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderHorizontal)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderVertical)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * End Sub
             */
            try
            {
                wdApp.Run("Сетка");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " Сетка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            //нумерация страниц
            Word.Window activeWindow = wdDoc.Application.ActiveWindow;
            object      currentPage  = Word.WdFieldType.wdFieldPage;
            object      totalPages   = Word.WdFieldType.wdFieldNumPages;

            //переход к редактированию футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
            activeWindow.ActivePane.Selection.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            //напечатает номер страницы в формате X стр. из Y
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref currentPage, ref wdMiss, ref wdMiss);
            activeWindow.Selection.TypeText(" стр. из ");
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref totalPages, ref wdMiss, ref wdMiss);
            //выход из футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

            //wdApp.Visible = true; //показать документ пользователю
        }
Пример #24
0
    public void ImprimirEtiquetasArreglos(JObject pJDocumento, int pIdImpresionTemplate, string pRutaTemplate, CConexion pConexion)
    {
        CImpresionEtiquetas         ImpresionEtiquetas = new CImpresionEtiquetas();
        Dictionary <string, object> Parametros         = new Dictionary <string, object>();

        Parametros.Add("IdImpresionTemplate", pIdImpresionTemplate);

        object oEndOfDoc = "\\endofdoc"; /* \endofdoc es un bookmark predefinido */
        Object oMissing  = System.Reflection.Missing.Value;

        Word.Range wrdRng = documentoWord.Bookmarks.get_Item(ref oEndOfDoc).Range;
        int        ind    = 0;
        object     oPos;
        double     dPos = aplicacionWord.InchesToPoints(10);

        foreach (JProperty oPropiedadDocumento in pJDocumento.Properties())
        {
            if (oPropiedadDocumento.Value.Type.ToString() == "Object")
            {
                JObject JTablaConceptos = new JObject();
                JTablaConceptos = (JObject)pJDocumento[oPropiedadDocumento.Name];
                foreach (JProperty oPropiedadTabla in JTablaConceptos.Properties())
                {
                    if (oPropiedadTabla.Name == "Tipo")
                    {
                        if (oPropiedadTabla.Value.ToString() == "Conceptos")
                        {
                            for (int i = 1; i <= documentoWord.Tables.Count; i++)
                            {
                                Word.Table wTable = documentoWord.Tables[i];
                                Word.Cell  pCell  = wTable.Cell(1, 1);

                                if (wTable.ID != null && wTable.ID == "tblReceptor")
                                {
                                    foreach (CImpresionEtiquetas oImpresionEtiqueta in ImpresionEtiquetas.LlenaObjetosFiltros(Parametros, pConexion))
                                    {
                                        Word.Range rangePlantilla = wTable.Range;

                                        int rc = wTable.Rows.Count;
                                        // Selecciona y copia el renglon Layout.
                                        rangePlantilla.Start = 1;
                                        rangePlantilla.End   = wTable.Rows[rc].Cells[wTable.Rows[rc].Cells.Count].Range.End;
                                        rangePlantilla.Find.ClearFormatting();
                                        rangePlantilla.Find.Text = oImpresionEtiqueta.Etiqueta;
                                        rangePlantilla.Find.Replacement.ClearFormatting();


                                        if (pJDocumento[oImpresionEtiqueta.Campo] != null)
                                        {
                                            rangePlantilla.Find.Replacement.Text = pJDocumento[oImpresionEtiqueta.Campo].ToString();
                                        }
                                        object replaceAll = Word.WdReplace.wdReplaceAll;
                                        rangePlantilla.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                                    }
                                }

                                if (wTable.ID != null && wTable.ID == JTablaConceptos["NombreTabla"].ToString())
                                {
                                    bool pRowsNum = false;
                                    if (wTable.Rows.Count > 1)
                                    {
                                        pRowsNum = true;
                                    }

                                    int contador = 1;
                                    // Layaout
                                    foreach (JObject JInventario in JTablaConceptos["Inventarios"])
                                    {
                                        contador = contador + 1;
                                        Word.Range range = wTable.Range;

                                        // Renglon Layout
                                        int selectedRow = 1;

                                        // Selecciona y copia el renglon Layout.
                                        range.Start = wTable.Rows[selectedRow].Cells[1].Range.Start;
                                        range.End   = wTable.Rows[selectedRow].Cells[wTable.Rows[selectedRow].Cells.Count].Range.End;
                                        range.Copy();

                                        // Inserta renglon nuevo al final de la tabla.
                                        wTable.Rows.Add(ref oMissing);

                                        // Mueve el cursor a la primera celda del renglon nuevo.
                                        range.Start = wTable.Rows[wTable.Rows.Count].Cells[1].Range.Start;
                                        range.End   = range.Start;

                                        // Pega los valores del renglon layout al renglon nuevo.
                                        range.Paste();

                                        int m = wTable.Rows.Count;

                                        Word.Row  renglonPlantilla = wTable.Rows[m];
                                        Word.Cell celdaPlantilla   = renglonPlantilla.Cells[1];

                                        for (int x = 1; x <= celdaPlantilla.Tables.Count; x++)
                                        {
                                            bool sRowsNum = false;
                                            if (celdaPlantilla.Tables[x].Rows.Count > 3)
                                            {
                                                sRowsNum = true;
                                            }
                                            foreach (CImpresionEtiquetas oImpresionEtiqueta in ImpresionEtiquetas.LlenaObjetosFiltros(Parametros, pConexion))
                                            {
                                                Word.Range rangePlantilla = wTable.Range;

                                                // Selecciona y copia el renglon Layout.
                                                rangePlantilla.Start = celdaPlantilla.Tables[x].Rows[1].Cells[1].Range.Start;
                                                rangePlantilla.End   = celdaPlantilla.Tables[x].Rows[1].Cells[celdaPlantilla.Tables[x].Rows[1].Cells.Count].Range.End;
                                                rangePlantilla.Find.ClearFormatting();
                                                rangePlantilla.Find.Text = oImpresionEtiqueta.Etiqueta;
                                                rangePlantilla.Find.Replacement.ClearFormatting();

                                                if (JInventario[oImpresionEtiqueta.Campo] != null)
                                                {
                                                    rangePlantilla.Find.Replacement.Text = JInventario[oImpresionEtiqueta.Campo].ToString();
                                                }
                                                object replaceAll = Word.WdReplace.wdReplaceAll;
                                                rangePlantilla.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                                            }

                                            foreach (JObject JConcepto in JInventario["Lista"])
                                            {
                                                Word.Range sRange = celdaPlantilla.Tables[x].Range;

                                                // Selecciona y copia el renglon Layout.
                                                sRange.Start = celdaPlantilla.Tables[x].Rows[3].Cells[1].Range.Start;
                                                sRange.End   = celdaPlantilla.Tables[x].Rows[3].Cells[celdaPlantilla.Tables[x].Rows[3].Cells.Count].Range.End;
                                                sRange.Copy();

                                                // Inserta renglon nuevo al final de la tabla.
                                                celdaPlantilla.Tables[x].Rows.Add(ref oMissing);

                                                // Mueve el cursor a la primera celda del renglon nuevo.
                                                sRange.Start = celdaPlantilla.Tables[x].Rows[celdaPlantilla.Tables[x].Rows.Count].Cells[1].Range.Start;
                                                sRange.End   = sRange.Start;

                                                // Pega los valores del renglon layout al renglon nuevo.
                                                sRange.Paste();

                                                foreach (CImpresionEtiquetas oImpresionEtiqueta in ImpresionEtiquetas.LlenaObjetosFiltros(Parametros, pConexion))
                                                {
                                                    Word.Range rowRange = wTable.Range;

                                                    // Selecciona y copia el renglon Layout.
                                                    sRange.Find.ClearFormatting();
                                                    sRange.Find.Text = oImpresionEtiqueta.Etiqueta;
                                                    sRange.Find.Replacement.ClearFormatting();

                                                    if (JConcepto[oImpresionEtiqueta.Campo] != null)
                                                    {
                                                        sRange.Find.Replacement.Text = JConcepto[oImpresionEtiqueta.Campo].ToString();
                                                    }
                                                    object replaceAll = Word.WdReplace.wdReplaceAll;
                                                    sRange.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                                                }
                                            }
                                            if (sRowsNum)
                                            {
                                                JObject JTotal = new JObject();
                                                JTotal = (JObject)JInventario["Total"];

                                                Word.Range sRange = celdaPlantilla.Tables[x].Range;

                                                // Selecciona y copia el renglon Layout.
                                                sRange.Start = celdaPlantilla.Tables[x].Rows[4].Cells[1].Range.Start;
                                                sRange.End   = celdaPlantilla.Tables[x].Rows[4].Cells[celdaPlantilla.Tables[x].Rows[4].Cells.Count].Range.End;
                                                sRange.Copy();

                                                // Inserta renglon nuevo al final de la tabla.
                                                celdaPlantilla.Tables[x].Rows.Add(ref oMissing);

                                                // Mueve el cursor a la primera celda del renglon nuevo.
                                                sRange.Start = celdaPlantilla.Tables[x].Rows[celdaPlantilla.Tables[x].Rows.Count].Cells[1].Range.Start;
                                                sRange.End   = sRange.Start;

                                                // Pega los valores del renglon layout al renglon nuevo.
                                                sRange.Paste();

                                                foreach (CImpresionEtiquetas oImpresionEtiqueta in ImpresionEtiquetas.LlenaObjetosFiltros(Parametros, pConexion))
                                                {
                                                    Word.Range rowRange = wTable.Range;

                                                    // Selecciona y copia el renglon Layout.
                                                    sRange.Find.ClearFormatting();
                                                    sRange.Find.Text = oImpresionEtiqueta.Etiqueta;
                                                    sRange.Find.Replacement.ClearFormatting();

                                                    if (JTotal[oImpresionEtiqueta.Campo] != null)
                                                    {
                                                        sRange.Find.Replacement.Text = JTotal[oImpresionEtiqueta.Campo].ToString();
                                                    }
                                                    object replaceAll = Word.WdReplace.wdReplaceAll;
                                                    sRange.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                                                }
                                                celdaPlantilla.Tables[x].Rows[4].Delete();
                                            }
                                            celdaPlantilla.Tables[x].Rows[3].Delete();
                                        }
                                    }

                                    if (pRowsNum)
                                    {
                                        Word.Range sRange = wTable.Range;

                                        // Selecciona y copia el renglon Layout.
                                        sRange.Start = wTable.Rows[2].Cells[1].Range.Start;
                                        sRange.End   = wTable.Rows[2].Cells[wTable.Rows[2].Cells.Count].Range.End;
                                        sRange.Copy();

                                        // Inserta renglon nuevo al final de la tabla.
                                        wTable.Rows.Add(ref oMissing);

                                        // Mueve el cursor a la primera celda del renglon nuevo.
                                        sRange.Start = wTable.Rows[wTable.Rows.Count].Cells[1].Range.Start;
                                        sRange.End   = sRange.Start;

                                        // Pega los valores del renglon layout al renglon nuevo.
                                        sRange.Paste();

                                        foreach (CImpresionEtiquetas oImpresionEtiqueta in ImpresionEtiquetas.LlenaObjetosFiltros(Parametros, pConexion))
                                        {
                                            Word.Range rangePlantilla = wTable.Range;

                                            // Selecciona y copia el renglon Layout.
                                            rangePlantilla.Find.ClearFormatting();
                                            rangePlantilla.Find.Text = oImpresionEtiqueta.Etiqueta;
                                            rangePlantilla.Find.Replacement.ClearFormatting();


                                            if (pJDocumento[oImpresionEtiqueta.Campo] != null)
                                            {
                                                rangePlantilla.Find.Replacement.Text = pJDocumento[oImpresionEtiqueta.Campo].ToString();
                                            }
                                            object replaceAll = Word.WdReplace.wdReplaceAll;
                                            rangePlantilla.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                                        }
                                        wTable.Rows[2].Delete();
                                    }
                                    wTable.Rows[1].Delete();
                                }
                            }
                        }
                    }
                }
            }
        }
    }
Пример #25
0
        public void FillRepotData(Word.Document wordDoc, ReportAllDetailsDocVm reportDocData, string verifiedBy, List <ImageHouse> imageHouses)
        {
            try
            {
                var sfc = reportDocData.SafetyFirstCheck;
                var cus = reportDocData.CustomerEquipmentActivity;

                if (sfc != null && cus != null)
                {
                    wordDoc.SelectContentControlsByTitle("sfc_Customer")[1].Range.Text          = GetValueOrSpace(sfc.ProjectName);
                    wordDoc.SelectContentControlsByTitle("sfc_ServiceEngineer")[1].Range.Text   = GetValueOrSpace(sfc.EngineerName);
                    wordDoc.SelectContentControlsByTitle("sfc_Job_No")[1].Range.Text            = GetValueOrSpace(sfc.JobOrderNumber);
                    wordDoc.SelectContentControlsByTitle("sfc_startdate")[1].Range.Text         = sfc.StartDate.ToString("dd/MM/yy");
                    wordDoc.SelectContentControlsByTitle("sfc_contactno")[1].Range.Text         = GetValueOrSpace(sfc.ContactNumber);
                    wordDoc.SelectContentControlsByTitle("sfc_sitesafetycontact")[1].Range.Text = GetValueOrSpace(sfc.SiteSafetyContact);
                    wordDoc.SelectContentControlsByTitle("sfc_addcomm")[1].Range.Text           = GetValueOrSpace(sfc.AdditionalComments);

                    if (!string.IsNullOrWhiteSpace(sfc.Participants))
                    {
                        var participants = sfc.Participants.Split('\n');
                        var firstFive    = string.Empty;
                        var secondFive   = string.Empty;
                        int midPoint     = participants.Length / 2;
                        for (int i = 0; i < participants.Length; i++)
                        {
                            if (i <= midPoint)
                            {
                                firstFive += participants[i] + '\n';
                            }
                            else
                            {
                                secondFive += participants[i] + '\n';
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(firstFive))
                        {
                            firstFive = firstFive.Remove(firstFive.LastIndexOf('\n'));
                            wordDoc.SelectContentControlsByTitle("sfc_participants")[1].Range.Text = firstFive;
                            wordDoc.SelectContentControlsByTitle("sfc_participants")[1].Range.ListFormat.ApplyNumberDefault();
                        }
                        if (!string.IsNullOrWhiteSpace(secondFive))
                        {
                            secondFive = secondFive.Remove(secondFive.LastIndexOf('\n'));
                            wordDoc.SelectContentControlsByTitle("sfc_participants_1")[1].Range.Text = secondFive;
                            wordDoc.SelectContentControlsByTitle("sfc_participants_1")[1].Range.ListFormat.ApplyNumberDefault();
                        }
                    }

                    wordDoc.SelectContentControlsByTitle("sfc_signdate")[1].Range.Text = sfc.SignDate?.ToString("dd/MM/yy");
                    var sfcDetails = sfc.SafetyFirstCheckDetails;
                    if (sfcDetails != null)
                    {
                        var sfcd1 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "STOP-THINK-ACT");
                        if (sfcd1 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_stopthinkact")[1].Checked = sfcd1.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_stopthinkact_rm")[1].Range.Text = GetValueOrSpace(sfcd1?.Remarks);
                        var sfcd2 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Permit to Work(PTW)");
                        if (sfcd2 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_ptw")[1].Checked = sfcd2.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_ptw_rm")[1].Range.Text = GetValueOrSpace(sfcd2.Remarks);
                        var sfcd3 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Fitness of Personnel");
                        if (sfcd3 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_fitness")[1].Checked = sfcd3.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_fitness_rm")[1].Range.Text = GetValueOrSpace(sfcd3.Remarks);
                        var sfcd4 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Work Area Evaluation");
                        if (sfcd4 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_workareaeval")[1].Checked = sfcd4.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_workareaeval_rm")[1].Range.Text = GetValueOrSpace(sfcd4.Remarks);
                        var sfcd5 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Evacuation Plan");
                        if (sfcd5 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_evalplan")[1].Checked = sfcd5.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_evalplan_rm")[1].Range.Text = GetValueOrSpace(sfcd5.Remarks);
                        var sfcd6 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Method Statement Review");
                        if (sfcd6 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_methstmtrev")[1].Checked = sfcd6.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_methstmtrev_rm")[1].Range.Text = GetValueOrSpace(sfcd6.Remarks);
                        var sfcd7 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Risk Assessment Review");
                        if (sfcd7 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_riskassessrev")[1].Checked = sfcd7.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_riskassessrev_rm")[1].Range.Text = GetValueOrSpace(sfcd7.Remarks);
                        var sfcd8 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Mandatory PPE");
                        if (sfcd8 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_madatoryppe")[1].Checked = sfcd8.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_madatoryppe_rm")[1].Range.Text = GetValueOrSpace(sfcd8.Remarks);
                        var sfcd9 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Condition of tools/gears");
                        if (sfcd9 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_cond_tools")[1].Checked = sfcd9.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_cond_tools_rm")[1].Range.Text = GetValueOrSpace(sfcd9.Remarks);
                        var sfcd10 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "First Aid");
                        if (sfcd10 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_firstaid")[1].Checked = sfcd10.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_firstaid_rm")[1].Range.Text = GetValueOrSpace(sfcd10.Remarks);
                    }
                    wordDoc.SelectContentControlsByTitle("Job_No_Header")[1].Range.Text = GetValueOrSpace(sfc.JobOrderNumber);
                    //wordDoc.SelectContentControlsByTitle("Sub_No_Header")[1].Range.Text = GetValueOrSpace(sfc.JobOrderNumber);

                    wordDoc.SelectContentControlsByTitle("Cea_Customer")[1].Range.Text            = GetValueOrSpace(sfc.ProjectName);
                    wordDoc.SelectContentControlsByTitle("Cea_ServiceEngineer")[1].Range.Text     = GetValueOrSpace(sfc.EngineerName);
                    wordDoc.SelectContentControlsByTitle("Cea_ReportNumber")[1].Range.Text        = GetValueOrSpace(sfc.JobOrderNumber);
                    wordDoc.SelectContentControlsByTitle("Cea_PreviousServiceDate")[1].Range.Text = cus.PreviousServiceDate.ToString("dd/MM/yy");
                    wordDoc.SelectContentControlsByTitle("Cea_CurrentServiceDate")[1].Range.Text  = cus.CurrentServiceDate.ToString("dd/MM/yy");
                    wordDoc.SelectContentControlsByTitle("Cea_ReportDate")[1].Range.Text          = cus.ReportDate.ToString("dd/MM/yy");
                    wordDoc.SelectContentControlsByTitle("Cea_SiteLocation")[1].Range.Text        = GetValueOrSpace(cus.SiteLocation);

                    var equipmentMapping = new Dictionary <string, string> {
                        { "decanter", "Decanter" }
                    };
                    if (equipmentMapping.TryGetValue(cus.Equipment, out string Equipment))
                    {
                        SelectValueFromDropDownSrc(wordDoc, "Cea_Equipment", Equipment);
                    }

                    //equipment details
                    wordDoc.SelectContentControlsByTitle("Cea_DecanterModel")[1].Range.Text        = GetValueOrSpace(cus.DecanterModel);
                    wordDoc.SelectContentControlsByTitle("Cea_DecanterSerialNumber")[1].Range.Text = GetValueOrSpace(cus.DecanterSerialNumber);
                    wordDoc.SelectContentControlsByTitle("Cea_BowlSerialNumber")[1].Range.Text     = GetValueOrSpace(cus.BowlSerialNumber);
                    wordDoc.SelectContentControlsByTitle("Cea_CustomerReference")[1].Range.Text    = GetValueOrSpace(cus.CustomerReference);
                    wordDoc.SelectContentControlsByTitle("Cea_RunningHours")[1].Range.Text         = cus.RunningHours.ToString();

                    wordDoc.SelectContentControlsByTitle("Cea_Controller")[1].Range.Text   = GetValueOrSpace(cus.Controller);
                    wordDoc.SelectContentControlsByTitle("Cea_HmiModel")[1].Range.Text     = GetValueOrSpace(cus.HmiModel);
                    wordDoc.SelectContentControlsByTitle("Cea_HmiSwVersion")[1].Range.Text = GetValueOrSpace(cus.HmiSwVersion);
                    wordDoc.SelectContentControlsByTitle("Cea_CpuModel")[1].Range.Text     = GetValueOrSpace(cus.CpuModel);
                    wordDoc.SelectContentControlsByTitle("Cea_CpuSwVersion")[1].Range.Text = GetValueOrSpace(cus.CpuSwVersion);

                    //if(KeyValue.controllerMapping.TryGetValue(cus.Controller, out string controller))
                    //    SelectValueFromDropDownSrc(wordDoc, "Cea_Controller", controller);

                    //if (KeyValue.hmiModelMapping.TryGetValue(cus.HmiModel, out string hmiModel))
                    //    SelectValueFromDropDownSrc(wordDoc, "Cea_HmiModel", hmiModel);

                    //if (KeyValue.HmiSwVersionMapping.TryGetValue(cus.HmiSwVersion, out string hmiSwVersion))
                    //    SelectValueFromDropDownSrc(wordDoc, "Cea_HmiSwVersion", hmiSwVersion);

                    //if (KeyValue.CpuModelMapping.TryGetValue(cus.CpuModel, out string CpuModel))
                    //    SelectValueFromDropDownSrc(wordDoc, "Cea_CpuModel", CpuModel);

                    //if (KeyValue.CpuSwVersionMapping.TryGetValue(cus.CpuSwVersion, out string CpuSwVersion))
                    //    SelectValueFromDropDownSrc(wordDoc, "Cea_CpuSwVersion", CpuSwVersion);

                    //Activity
                    if (KeyValue.ScopeOfWrokMapping.TryGetValue(cus.ScopeOfWrok, out string ScopeOfWrok))
                    {
                        SelectValueFromDropDownSrc(wordDoc, "Cea_ScopeOfWrok", ScopeOfWrok);
                    }
                    wordDoc.SelectContentControlsByTitle("Cea_ScoperOfWorkOthers")[1].Range.Text = GetValueOrSpace(cus.ScoperOfWorkOthers);

                    if (KeyValue.WorkStatusMapping.TryGetValue(cus.WorkStatus, out string WorkStatus))
                    {
                        SelectValueFromDropDownSrc(wordDoc, "Cea_WorkStatus", WorkStatus);
                    }

                    if (KeyValue.DecanterStatusMapping.TryGetValue(cus.DecanterStatus, out string DecanterStatus))
                    {
                        SelectValueFromDropDownSrc(wordDoc, "Cea_DecanterStatus", DecanterStatus);
                    }
                }

                //Vibration Analysis Report
                var vibAna = reportDocData.VibrationAnalysisHeader;
                if (vibAna != null)
                {
                    wordDoc.SelectContentControlsByTitle($"Vah_BsDryRunActive")[1].Checked = vibAna.BsDryRunActive;
                    wordDoc.SelectContentControlsByTitle($"Vah_BsProduction")[1].Checked   = vibAna.BsProduction;
                    wordDoc.SelectContentControlsByTitle($"Vah_AsDryRun")[1].Checked       = vibAna.AsDryRun;
                    wordDoc.SelectContentControlsByTitle($"Vah_AsWaterTest")[1].Checked    = vibAna.AsWaterTest;
                    wordDoc.SelectContentControlsByTitle($"Vah_AsProduction")[1].Checked   = vibAna.AsProduction;

                    if (vibAna.VibrationAnalysis != null && vibAna.VibrationAnalysis.Count > 0)
                    {
                        foreach (var pu in KeyValue.parameterUnits)
                        {
                            var param = vibAna.VibrationAnalysis?.Where(w => $"{w.Parameter}~{w.Units}" == pu.Value).FirstOrDefault();
                            if (param != null)
                            {
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_Bs_DryRun")[1].Range.Text = GetValueOrSpace(param.BsDryRun);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_Bs_Prod")[1].Range.Text   = GetValueOrSpace(param.BsProduction);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_As_DryRun")[1].Range.Text = GetValueOrSpace(param.AsDryRun);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_As_Water")[1].Range.Text  = GetValueOrSpace(param.AsWaterTest);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_As_Prod")[1].Range.Text   = GetValueOrSpace(param.AsProduction);
                            }
                            else
                            {
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_Bs_DryRun")[1].Delete(true);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_Bs_Prod")[1].Delete(true);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_As_DryRun")[1].Delete(true);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_As_Water")[1].Delete(true);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_As_Prod")[1].Delete(true);
                            }
                        }
                    }

                    wordDoc.SelectContentControlsByTitle($"Md_Check")[1].Checked = vibAna.MdMotor;
                    wordDoc.SelectContentControlsByTitle($"Bd_Check")[1].Checked = vibAna.BdMotor;

                    wordDoc.SelectContentControlsByTitle($"Md_DE_Main")[1].Range.Text  = GetValueOrSpace(vibAna.MdDriveEndMain);
                    wordDoc.SelectContentControlsByTitle($"Md_NDE_Main")[1].Range.Text = GetValueOrSpace(vibAna.MdNonDriveEndMain);
                    wordDoc.SelectContentControlsByTitle($"Md_DE_Back")[1].Range.Text  = GetValueOrSpace(vibAna.MdDriveEndBack);
                    wordDoc.SelectContentControlsByTitle($"Md_NDE_Back")[1].Range.Text = GetValueOrSpace(vibAna.MdNonDriveEndBack);
                    wordDoc.SelectContentControlsByTitle($"Bd_DE_Main")[1].Range.Text  = GetValueOrSpace(vibAna.BdDriveEndMain);
                    wordDoc.SelectContentControlsByTitle($"Bd_NDE_Main")[1].Range.Text = GetValueOrSpace(vibAna.BdNonDriveEndMain);
                    wordDoc.SelectContentControlsByTitle($"Bd_DE_Back")[1].Range.Text  = GetValueOrSpace(vibAna.BdDriveEndBack);
                    wordDoc.SelectContentControlsByTitle($"Bd_NDE_Back")[1].Range.Text = GetValueOrSpace(vibAna.BdNonDriveEndBack);
                    wordDoc.SelectContentControlsByTitle("Vah_Remarks")[1].Range.Text  = GetValueOrSpace(vibAna.Remarks);
                    if (!string.IsNullOrWhiteSpace(vibAna.Remarks))
                    {
                        wordDoc.SelectContentControlsByTitle("Vah_Remarks")[1].Range.Font.Color = Word.WdColor.wdColorRed;
                    }
                }

                bool pageBreakedRecomm     = false;
                bool pageBreakedObs        = false;
                bool pageBreakedSpareParts = false;


                #region Recommendations
                var recommTableIndex = 0;

                for (int i = 1; i <= wordDoc.Tables.Count; i++)
                {
                    if (wordDoc.Tables[i].Title == "RecommHead")
                    {
                        recommTableIndex = i;
                        break;
                    }
                }
                if (recommTableIndex > 0 && reportDocData.Recommendations != null && reportDocData.Recommendations.Count > 0)
                {
                    wordDoc.Tables[recommTableIndex].Range.InsertBreak();
                    pageBreakedRecomm = true;
                    int sno = 1;
                    foreach (var recomm in reportDocData.Recommendations)
                    {
                        var row = wordDoc.Tables[recommTableIndex].Rows.Add();
                        row.Height     = 30.0f; //1.2 cm
                        row.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
                        row.Shading.BackgroundPatternColor = Word.WdColor.wdColorWhite;

                        row.Cells[1].Range.Text      = $"0{sno}";
                        row.Cells[1].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                        row.Cells[1].Range.Font.Bold = 0;

                        row.Cells[2].Range.Text      = GetValueOrSpace(recomm.Remarks);
                        row.Cells[2].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                        row.Cells[2].Range.Font.Bold = 0;
                        row.Cells[2].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

                        row.Cells[3].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox).Checked = recomm.ImmediateAction;
                        row.Cells[4].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox).Checked = recomm.MidTermAction;
                        row.Cells[5].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox).Checked = recomm.Observation;
                        sno++;
                        //InsertOrRemoveImage(wordDoc, $"Recomm_Pic_{i}", recomm.EntityRefGuid, imageHouses);
                    }
                }
                else
                {
                    //wordDoc.SelectContentControlsByTitle("RecommHead")[1].Delete(true);
                    //if (recommTableIndex > 0)
                    //    wordDoc.Tables[recommTableIndex].Delete();

                    //Client Req:Recommendations can be added. But the page is getting skipped in Report
                    var row = wordDoc.Tables[recommTableIndex].Rows.Add();
                    row.Height     = 30.0f; //1.2 cm
                    row.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
                    row.Shading.BackgroundPatternColor = Word.WdColor.wdColorWhite;

                    row.Cells[1].Range.Text      = $"0{1}";
                    row.Cells[1].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                    row.Cells[1].Range.Font.Bold = 0;

                    row.Cells[2].Range.Text      = string.Empty;
                    row.Cells[2].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                    row.Cells[2].Range.Font.Bold = 0;
                    row.Cells[2].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

                    row.Cells[3].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox).Checked = false;
                    row.Cells[4].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox).Checked = false;
                    row.Cells[5].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox).Checked = false;

                    pageBreakedRecomm = true;
                }
                #endregion

                #region Observations
                var obserTableIndex = 0;
                for (int i = 1; i <= wordDoc.Tables.Count; i++)
                {
                    if (wordDoc.Tables[i].Title == "ObsHead")
                    {
                        obserTableIndex = i;
                        break;
                    }
                }

                if (obserTableIndex > 0 && reportDocData.Observations != null &&
                    reportDocData.Observations.Count > 0)
                {
                    if (pageBreakedRecomm)
                    {
                        wordDoc.Tables[obserTableIndex].Range.InsertBreak();
                    }

                    pageBreakedObs = true;
                    int iteration = 0;
                    foreach (var obs in reportDocData.Observations)
                    {
                        //if (!KeyValue.observation.ContainsKey(obs.Title))
                        //    continue;

                        Word.Row row1 = null;
                        Word.Row row2 = null;
                        if (iteration > 0)
                        {
                            row1 = wordDoc.Tables[obserTableIndex].Rows.Add();
                            row2 = wordDoc.Tables[obserTableIndex].Rows.Add();
                        }
                        else
                        {
                            row1 = wordDoc.Tables[obserTableIndex].Rows[1];
                            row2 = wordDoc.Tables[obserTableIndex].Rows.Add();
                        }
                        row1.Height     = 30.0f;
                        row1.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;

                        row2.Height     = 30.0f;
                        row2.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;

                        row1.Borders[Word.WdBorderType.wdBorderTop].LineStyle    = Word.WdLineStyle.wdLineStyleDouble;
                        row2.Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleDouble;

                        //row1
                        row1.Cells[1].Range.Text = obs.Title;

                        string remark = $"Observations:";
                        if (!string.IsNullOrWhiteSpace(obs.Remarks))
                        {
                            remark = $"Observations:\n{obs.Remarks}";
                        }
                        row1.Cells[2].Range.Text      = remark;
                        row1.Cells[2].Range.Font.Bold = 0;
                        row1.Cells[2].Range.ListFormat.ApplyBulletDefault();

                        //making Observations: as Bold & removing bullet
                        object     objStart = row1.Cells[2].Range.Start;
                        object     objEnd   = row1.Cells[2].Range.Start + remark.IndexOf(":");
                        Word.Range rngBold  = wordDoc.Range(ref objStart, ref objEnd);
                        rngBold.Bold = 1;
                        rngBold.ListFormat.RemoveNumbers();

                        //row2
                        string imagePath = GetImagePath(obs.EntityRefGuid, imageHouses);

                        if (!string.IsNullOrWhiteSpace(imagePath) && System.IO.File.Exists(imagePath))
                        {
                            row2.Height     = 120.0f;
                            row2.HeightRule = Word.WdRowHeightRule.wdRowHeightExactly;

                            row2.Cells[1].Range.ContentControls
                            .Add(Word.WdContentControlType.wdContentControlPicture).Range
                            .InlineShapes.AddPicture(imagePath);
                        }
                        string actionTaken = $"Action Taken:";
                        if (!string.IsNullOrWhiteSpace(obs.ActionTaken))
                        {
                            actionTaken = $"Action Taken: {obs.ActionTaken}";
                        }

                        row2.Cells[2].Range.Text      = actionTaken;
                        row2.Cells[2].Range.Font.Bold = 0;
                        row2.Cells[2].Range.ListFormat.ApplyBulletDefault();

                        //making Action Taken: as Bold & removing bullet
                        object     objStart1 = row2.Cells[2].Range.Start;
                        object     objEnd1   = row2.Cells[2].Range.Start + actionTaken.IndexOf(":");
                        Word.Range rngBold1  = wordDoc.Range(ref objStart1, ref objEnd1);
                        rngBold1.Bold = 1;
                        rngBold1.ListFormat.RemoveNumbers();

                        iteration++;
                    }

                    #region Merging Cells
                    Word.Table table = wordDoc.Tables[obserTableIndex];
                    Word.Cell  cell;
                    int        rowIndex     = 1;
                    int        blockIndex   = table.Rows.Count / 2;
                    int        coloumnIndex = 1;

                    for (int blockCounter = 1; blockCounter <= blockIndex; blockCounter++)
                    {
                        for (int colCounter = 1; colCounter <= coloumnIndex; colCounter++)
                        {
                            cell = table.Cell(rowIndex, colCounter);
                            cell.Merge(table.Cell(cell.RowIndex + 1, colCounter));
                        }
                        rowIndex += 2;
                    }
                    #endregion
                }
                else
                {
                    wordDoc.SelectContentControlsByTitle("ObsHead")[1].Delete(true);
                    if (obserTableIndex > 0)
                    {
                        wordDoc.Tables[obserTableIndex].Delete();
                    }
                }
                #endregion

                #region Spare Parts
                var sparePartTypes = new string[] { "USED", "RECOM" };
                int sparePartIter  = 0;
                foreach (var sparePart in sparePartTypes)
                {
                    var sparePartsTableIndex = 0;

                    for (int i = 1; i <= wordDoc.Tables.Count; i++)
                    {
                        if (wordDoc.Tables[i].Title == sparePart)
                        {
                            sparePartsTableIndex = i;
                            break;
                        }
                    }
                    if (sparePartsTableIndex > 0 && reportDocData.SpareParts != null && reportDocData.SpareParts.Count > 0)
                    {
                        if (sparePartIter == 0)
                        {
                            wordDoc.Tables[sparePartsTableIndex].Range.InsertBreak();
                            pageBreakedSpareParts = true;
                            sparePartIter++;
                        }

                        int sno = 1;
                        foreach (var sp in reportDocData.SpareParts.Where(w => sparePart.Equals(w.Type, StringComparison.OrdinalIgnoreCase)))
                        {
                            var row = wordDoc.Tables[sparePartsTableIndex].Rows.Add();
                            row.Height     = 25.0f; //1.0 cm
                            row.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
                            row.Shading.BackgroundPatternColor = Word.WdColor.wdColorWhite;

                            row.Cells[1].Range.Text      = $"{sno}";
                            row.Cells[1].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                            row.Cells[1].Range.Font.Bold = 0;

                            row.Cells[2].Range.Text      = GetValueOrSpace(sp.Description);
                            row.Cells[2].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                            row.Cells[2].Range.Font.Bold = 0;
                            row.Cells[2].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

                            row.Cells[3].Range.Text      = GetValueOrSpace(sp.PartNo);
                            row.Cells[3].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                            row.Cells[3].Range.Font.Bold = 0;
                            row.Cells[3].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

                            row.Cells[4].Range.Text      = sp.Quantity.ToString();
                            row.Cells[4].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                            row.Cells[4].Range.Font.Bold = 0;
                            row.Cells[4].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                            sno++;
                        }
                    }
                    else
                    {
                        //wordDoc.SelectContentControlsByTitle(sparePart)[1].Delete(true);
                        if (sparePartsTableIndex > 0)
                        {
                            wordDoc.Tables[sparePartsTableIndex].Delete();
                        }
                    }
                }

                #endregion

                //Ack //misc --SignCommSection
                var commTableIndex = 0;
                for (int i = 1; i <= wordDoc.Tables.Count; i++)
                {
                    if (wordDoc.Tables[i].Title == "SignCommSection")
                    {
                        commTableIndex = i;
                        break;
                    }
                }
                if (pageBreakedObs || pageBreakedRecomm || pageBreakedSpareParts)
                {
                    wordDoc.Tables[commTableIndex].Range.InsertBreak();
                }

                var miscData = reportDocData.Misc;
                if (miscData != null)
                {
                    wordDoc.SelectContentControlsByTitle($"misc_firmcomm")[1].Range.Text = GetValueOrSpace(miscData.FirmComments);
                    wordDoc.SelectContentControlsByTitle($"misc_custcomm")[1].Range.Text = GetValueOrSpace(miscData.CustomerComments);
                    wordDoc.SelectContentControlsByTitle($"Alfa_Ack_Name")[1].Range.Text = GetValueOrSpace(miscData.FirmName);
                    wordDoc.SelectContentControlsByTitle($"Alfa_Ack_Date")[1].Range.Text = miscData.FirmDate.ToString("dd/MM/yy");
                    wordDoc.SelectContentControlsByTitle($"Cust_Ack_Name")[1].Range.Text = GetValueOrSpace(miscData.CustomerName);
                    wordDoc.SelectContentControlsByTitle($"Cust_Ack_Date")[1].Range.Text = miscData.CustomerDate.ToString("dd/MM/yy");;
                }
                var firmSignature = imageHouses.FirstOrDefault(w => w.ImageLabel == StringConstants.FirmSignature);
                if (firmSignature != null)
                {
                    InsertOrRemoveImage(wordDoc, "firm_sign", firmSignature.EntityRefGuid, imageHouses);
                }
                var custSignature = imageHouses.FirstOrDefault(w => w.ImageLabel == StringConstants.CustomerSignature);
                if (custSignature != null)
                {
                    InsertOrRemoveImage(wordDoc, "cust_sign", custSignature.EntityRefGuid, imageHouses);
                }

                var sfc_firmSignature = imageHouses.FirstOrDefault(w => w.ImageLabel == StringConstants.SfcFirmSignature);
                if (sfc_firmSignature != null)
                {
                    InsertOrRemoveImage(wordDoc, "sfc_firmsign", sfc_firmSignature.EntityRefGuid, imageHouses);
                }
                var sfc_custSignature = imageHouses.FirstOrDefault(w => w.ImageLabel == StringConstants.SfcCustomerSignature);
                if (sfc_custSignature != null)
                {
                    InsertOrRemoveImage(wordDoc, "sfc_customersign", sfc_custSignature.EntityRefGuid, imageHouses);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #26
0
        public void PrintForm4()
        {
            string select = @"SELECT [Group].groupName, count(Student.name)
                              FROM Student INNER JOIN
                              [Group] ON Student.idGroup = [Group].id
                              WHERE ((Student.id_comm = 2) AND (prikazNumKval = '') AND (prikazNumOut = '')) 
                              GROUP BY groupName";

            DataSet ds1 = new DataSet();

            try
            {
                ds1 = Util.FillTable("Student", select);
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }

            Word.Application wdApp  = new Word.Application();
            Word.Document    wdDoc  = new Word.Document();
            Object           wdMiss = System.Reflection.Missing.Value;

            wdDoc = wdApp.Documents.Add(ref wdMiss, ref wdMiss, ref wdMiss, ref wdMiss);
            //wdApp.Visible = true; //сначала формируется документ, показывать потом
            wdDoc.PageSetup.LeftMargin   = 40;
            wdDoc.PageSetup.RightMargin  = 25;
            wdDoc.PageSetup.TopMargin    = 20;
            wdDoc.PageSetup.BottomMargin = 20;
            Word.Table tb;
            Word.Range _range;

            int columnsCount = 4;

            tb = wdDoc.Tables.Add(wdApp.Selection.Range, ds1.Tables[0].Rows.Count + 3, columnsCount);
            tb.Columns[1].Width = 40;
            tb.Rows[1].Height   = 30;
            tb.Columns[2].Width = 120;
            tb.Rows[2].Height   = 30;
            tb.Columns[3].Width = 80;
            tb.Rows[3].Height   = 40;
            tb.Columns[4].Width = 300;

            Word.Row  row       = tb.Rows[1];
            Word.Cell firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }
            row       = tb.Rows[2];
            firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }

            tb.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wdApp.Selection.Range.Font.Name            = "Times New Roman";
            wdApp.Selection.Range.Font.Size            = 10;
            wdApp.Selection.Cells.VerticalAlignment    = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 0;

            tb.Cell(1, 1).Select();
            wdApp.Selection.Range.Font.Size = 14;
            wdApp.Selection.Font.Bold       = 1;
            tb.Cell(1, 1).Range.Text        = "Список";
            tb.Rows[2].Select();
            wdApp.Selection.Range.Font.Size = 12;
            wdApp.Selection.Font.Bold       = 1;
            tb.Cell(2, 1).Range.Text        = "студентов, обучающихся на коммерческой основе на " + DateTime.Now.ToShortDateString() + " г.";

            tb.Rows[3].Select();
            wdApp.Selection.Font.Bold = 1;
            tb.Cell(3, 1).Range.Text  = "№ п/п";
            tb.Cell(3, 2).Range.Text  = "Группа";
            tb.Cell(3, 3).Range.Text  = "Количество";
            tb.Cell(3, 4).Range.Text  = "Примечание";


            int rowCount  = 3;
            int rowNumber = 0;

            foreach (DataRow str in ds1.Tables[0].Rows)
            {
                rowCount++;
                rowNumber++;
                tb.Cell(rowCount, 1).Range.Text = rowNumber.ToString() + ".";
                tb.Cell(rowCount, 2).Range.Text = str.ItemArray[0].ToString();
                tb.Cell(rowCount, 3).Range.Text = str.ItemArray[1].ToString(); //количество студентов в группе
            }

            _range = wdDoc.Range(tb.Cell(4, 2).Range.Start, tb.Cell(rowCount, 2).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 10;
            _range = wdDoc.Range(tb.Cell(4, 4).Range.Start, tb.Cell(rowCount, 4).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 10;
            _range = wdDoc.Range(tb.Cell(3, 1).Range.Start, tb.Cell(rowCount, columnsCount).Range.End);
            _range.Select();

            /* вызов макроса для отображения границ таблицы
             * Sub Сетка()
             * 'Сетка макрос
             * With Selection.Borders(wdBorderTop)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderLeft)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderBottom)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderRight)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderHorizontal)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderVertical)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * End Sub
             */
            try
            {
                wdApp.Run("Сетка");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " Сетка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            //нумерация страниц
            Word.Window activeWindow = wdDoc.Application.ActiveWindow;
            object      currentPage  = Word.WdFieldType.wdFieldPage;
            object      totalPages   = Word.WdFieldType.wdFieldNumPages;

            //переход к редактированию футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
            activeWindow.ActivePane.Selection.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            //напечатает номер страницы в формате X стр. из Y
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref currentPage, ref wdMiss, ref wdMiss);
            activeWindow.Selection.TypeText(" стр. из ");
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref totalPages, ref wdMiss, ref wdMiss);
            //выход из футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

            wdApp.Visible = true; //показать документ пользователю
        }
Пример #27
0
 public void updateDoc(Dictionary <string, Object> keyValuePairs)
 {
     Word.Application wordApp = new Word.Application();
     Word.Document    doc     = wordApp.Documents.Open(documentPath, ReadOnly: false);
     try {
         doc.Activate();
         if (((string)(keyValuePairs["{id:kind}"])).Contains("Тренировк") || ((string)(keyValuePairs["{id:kind}"])).Contains("Самостояте") || ((string)(keyValuePairs["{id:kind}"])).Contains("Практическо"))
         {
             int countQuestions = 0;
             for (int e = 1; e <= doc.Paragraphs.Count; e++)
             {
                 if (doc.Paragraphs[e].Range.Text.Contains("{id:adjunct}"))
                 {
                     Dictionary <string, string> questions = (Dictionary <string, string>)(keyValuePairs["{id:questions}"]);
                     FindAndReplace(wordApp, "{id:adjunct}", "ПРИЛОЖЕНИЯ");
                     countQuestions = questions.Count;
                     Word.Paragraph p = doc.Paragraphs[e];
                     p.Range.InsertParagraphAfter();
                     p = p.Next();
                     for (int i = 0; i < questions.Count; i++)
                     {
                         p.Range.Text = (i + 1) + ". Карточка - задание на изучение " + (i + 1) + "-го вопроса.";
                         p.Range.InsertParagraphAfter();
                         p = p.Next();
                     }
                 }
                 int q           = 1;
                 int countTables = doc.Tables.Count;
                 if (doc.Paragraphs[e].Range.Text.Contains("{id:file"))
                 {
                     Word.Paragraph p = doc.Paragraphs[e];
                     p.Range.InsertParagraphAfter();
                     p.Next();
                     Dictionary <string, string> questions = (Dictionary <string, string>)(keyValuePairs["{id:questions}"]);
                     int temp = Int32.Parse(doc.Paragraphs[e].Range.Text.Trim().Replace("\r", "").Replace("\a", "").Replace("\n", "").Substring(8, 1));
                     KeyValuePair <string, string> question;
                     try
                     {
                         question = questions.ElementAt(temp - 1);
                     }
                     catch (Exception exception)
                     {
                         break;
                     }
                     p.Range.InsertFile(Path.GetFullPath(Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, @"../../../../../Resources/AdditionalDocs/Spravochnik.docx")));
                     int z = 0;
                     for (int i = 0; i < question.Key.Length; i += 30)
                     {
                         if (i > 0)
                         {
                             try
                             {
                                 FindAndReplace(wordApp, "{id:questionName}", question.Key.Substring(i + 1, 30) + "{id:questionName}");
                             }
                             catch (Exception qq)
                             {
                                 break;
                             }
                         }
                         else
                         {
                             FindAndReplace(wordApp, "{id:questionName}", question.Key.Substring(i, 30) + "{id:questionName}");
                         }
                         z = i;
                     }
                     z += 30;
                     FindAndReplace(wordApp, "{id:questionName}", question.Key.Substring(z + 1));
                     FindAndReplace(wordApp, "{id:countAjunct}", temp);
                     FindAndReplace(wordApp, "{id:questionDuration}", question.Value.Split(separator)[0]);
                 }
                 int afterInsert = doc.Tables.Count;
             }
         }
         if (((string)(keyValuePairs["{id:kind}"])).ToLower().Contains("полувз") || ((string)(keyValuePairs["{id:kind}"])).ToLower().Contains("ПРО 3 ЧЕЛОВЕК СПРОСИТЬ КАК НАЗЫВАЕТСЯ"))
         {
             foreach (Word.Paragraph paragraph in doc.Paragraphs)
             {
                 if (paragraph.Range.Text.Contains("{id:image}"))
                 {
                     if (((string)(keyValuePairs["{id:kind}"])).ToLower().Contains("ПРО 3 ЧЕЛОВЕК СПРОСИТЬ КАК НАЗЫВАЕТСЯ"))
                     {
                         paragraph.Range.InsertFile(Path.GetFullPath(Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, @"../../../../../Resources/AdditionalDocs/image2.docx")));
                     }
                     else
                     {
                         paragraph.Range.InsertFile(Path.GetFullPath(Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, @"../../../../../Resources/AdditionalDocs/image1.docx")));
                     }
                 }
             }
         }
         FindAndReplace(wordApp, "{id:cardOfTask}", "");
         FindAndReplace(wordApp, "{id:file1}", "");
         FindAndReplace(wordApp, "{id:file2}", "");
         FindAndReplace(wordApp, "{id:file3}", "");
         FindAndReplace(wordApp, "{id:file4}", "");
         FindAndReplace(wordApp, "{id:file5}", "");
         FindAndReplace(wordApp, "{id:file6}", "");
         FindAndReplace(wordApp, "{id:image}", "");
         FindAndReplace(wordApp, "{id:name}", keyValuePairs["{id:name}"]);
         FindAndReplace(wordApp, "{id:theme}", keyValuePairs["{id:theme}"]);
         FindAndReplace(wordApp, "{id:themeName}", keyValuePairs["{id:themeName}"]);
         FindAndReplace(wordApp, "{id:lesson}", keyValuePairs["{id:lesson}"]);
         FindAndReplace(wordApp, "{id:lessonName}", keyValuePairs["{id:lessonName}"]);
         FindAndReplace(wordApp, "{id:kind}", keyValuePairs["{id:kind}"]);
         FindAndReplace(wordApp, "{id:method}", keyValuePairs["{id:method}"]);
         FindAndReplace(wordApp, "{id:duration}", keyValuePairs["{id:duration}"]);
         FindAndReplace(wordApp, "{id:place}", keyValuePairs["{id:place}"]);
         string methodical = (string)keyValuePairs["{id:methodical}"];
         int    k          = 0;
         for (int i = 0; i < methodical.Length; i += 30)
         {
             if (i > 0)
             {
                 try
                 {
                     FindAndReplace(wordApp, "{id:methodical}", methodical.Substring(i + 1, 30) + "{id:methodical}");
                 }
                 catch (Exception e)
                 {
                     break;
                 }
             }
             else
             {
                 FindAndReplace(wordApp, "{id:methodical}", methodical.Substring(i, 30) + "{id:methodical}");
             }
             k = i;
         }
         k += 30;
         FindAndReplace(wordApp, "{id:methodical}", methodical.Substring(k + 1));
         string literature = (string)keyValuePairs["{id:literature}"];
         int    l          = 0;
         for (int i = 0; i < literature.Length; i += 30)
         {
             if (i > 0)
             {
                 try
                 {
                     FindAndReplace(wordApp, "{id:literature}", literature.Substring(i + 1, 30) + "{id:literature}");
                 }
                 catch (Exception e)
                 {
                     break;
                 }
             }
             else
             {
                 FindAndReplace(wordApp, "{id:literature}", literature.Substring(i, 30) + "{id:literature}");
             }
             l = i;
         }
         l += 30;
         FindAndReplace(wordApp, "{id:literature}", literature.Substring(l + 1));
         FindAndReplace(wordApp, "{id:technicalMeans}", keyValuePairs["{id:technicalMeans}"]);
         string introTime = (keyValuePairs["{id:intro}"]).ToString().Split(separator)[0];
         FindAndReplace(wordApp, "{id:intro}", introTime);
         string[] introQuestions = (keyValuePairs["{id:intro}"]).ToString().Split(separator)[1].Split(';');
         for (int e = 0; e < introQuestions.Length - 1; e++)
         {
             FindAndReplace(wordApp, "{id:introQuestions}", introQuestions[e] + ";\r\n{id:introQuestions}");
         }
         FindAndReplace(wordApp, "{id:introQuestions}", "");
         FindAndReplace(wordApp, "{id:material}", keyValuePairs["{id:material}"]);
         FindAndReplace(wordApp, "{id:educationalQuestions}", keyValuePairs["{id:educationalQuestions}"]);
         string conclusionTime = (keyValuePairs["{id:conclution}"]).ToString().Split(separator)[0];
         FindAndReplace(wordApp, "{id:conclution}", conclusionTime);
         string[] conclusionQuestions = (keyValuePairs["{id:conclution}"]).ToString().Split(separator)[1].Split(';');
         for (int e = 0; e < conclusionQuestions.Length - 1; e++)
         {
             FindAndReplace(wordApp, "{id:conclutionsQuestions}", conclusionQuestions[e] + ";\r\n{id:conclutionsQuestions}");
         }
         FindAndReplace(wordApp, "{id:conclutionsQuestions}", "");
         foreach (Word.Table table in doc.Tables)
         {
             Word.Range rangeTable = table.Range;
             foreach (Word.Row row in rangeTable.Rows)
             {
                 foreach (Word.Cell cell in row.Cells)
                 {
                     Word.Range range = cell.Range;
                     if (range.Text.Contains("{id:questions}"))
                     {
                         FindAndReplace(wordApp, "{id:questions}", "");
                         Word.Row temporary = row;
                         int      count     = 1;
                         foreach (KeyValuePair <string, string> question in (Dictionary <string, string>)keyValuePairs["{id:questions}"])
                         {
                             Object   oMissing = System.Reflection.Missing.Value;
                             Word.Row newRow   = table.Rows.Add(ref oMissing);
                             newRow.Cells[1].Range.Text = "2." + count;
                             newRow.Cells[2].Range.Text = question.Key;
                             newRow.Cells[3].Range.Text = question.Value.Split(separator)[0];
                             Regex  regex        = new Regex("^ ?[1-9].*$");
                             string questionFull = "";
                             if (regex.IsMatch(question.Key))
                             {
                                 questionFull = "Учебный вопрос. " + question.Key + " " + question.Value.Split(separator)[0] + ".\r\n";
                             }
                             else
                             {
                                 questionFull = "Учебный вопрос " + count + ". " + question.Key + " " + question.Value.Split(separator)[0] + ".\r\n";
                             }
                             int r = 0;
                             for (int e = 0; e < questionFull.Length; e += 30)
                             {
                                 if (e > 0)
                                 {
                                     try
                                     {
                                         FindAndReplace(wordApp, "{id:questionOfLesson}", questionFull.Substring(e, 30) + "{id:questionOfLesson}");
                                     }
                                     catch (Exception q)
                                     {
                                         break;
                                     }
                                 }
                                 else
                                 {
                                     FindAndReplace(wordApp, "{id:questionOfLesson}", questionFull.Substring(e, 30) + "{id:questionOfLesson}");
                                 }
                                 r = e;
                             }
                             r += 30;
                             FindAndReplace(wordApp, "{id:questionOfLesson}", questionFull.Substring(r) + "\r\n{id:contentOfQuestion}");
                             int    w    = 0;
                             string temp = question.Value.Split(separator)[1];
                             if (temp.Length > 30)
                             {
                                 for (int z = 0; z < temp.Length; z += 30)
                                 {
                                     if (z > 0)
                                     {
                                         try
                                         {
                                             FindAndReplace(wordApp, "{id:contentOfQuestion}", temp.Substring(z, 30) + "{id:contentOfQuestion}");
                                         }
                                         catch (Exception q)
                                         {
                                             break;
                                         }
                                     }
                                     else
                                     {
                                         FindAndReplace(wordApp, "{id:contentOfQuestion}", temp.Substring(z, 30) + "{id:contentOfQuestion}");
                                     }
                                     w = z;
                                 }
                                 FindAndReplace(wordApp, "{id:contentOfQuestion}", temp.Substring(w) + "\r\n{id:questionOfLesson}\r\n");
                                 temporary = newRow;
                                 count++;
                             }
                             else
                             {
                                 FindAndReplace(wordApp, "{id:contentOfQuestion}", temp.Substring(w) + "\r\n{id:questionOfLesson}\r\n");
                                 count++;
                             }
                         }
                         Object   missing   = System.Reflection.Missing.Value;
                         Word.Row newRowENd = table.Rows.Add(ref missing);
                         newRowENd.Cells[1].Range.Text = "3";
                         newRowENd.Cells[2].Range.Text = "Заключение";
                         newRowENd.Cells[3].Range.Text = (string)keyValuePairs["{id:conclution}"].ToString().Split(separator)[0] + " мин";
                     }
                     else if (range.Text.Contains("{id:goal}"))
                     {
                         FindAndReplace(wordApp, "{id:goal}", "");
                         int count = 1;
                         foreach (string goal in (List <string>)keyValuePairs["{id:goal}"])
                         {
                             Object   oMissing = System.Reflection.Missing.Value;
                             Word.Row newRow   = table.Rows.Add(ref oMissing);
                             newRow.Cells[1].Range.Text = count + "";
                             newRow.Cells[2].Range.Text = goal;
                             count++;
                         }
                     }
                 }
             }
         }
         FindAndReplace(wordApp, "{id:adjunct}", "");
         FindAndReplace(wordApp, "{id:questionOfLesson}", "");
         WordAPI.SaveFile(doc);
         WordAPI.Close(doc);
         updatePlan(keyValuePairs);
     }
     catch (Exception e)
     {
         doc.Close();
         new ExceptionWindow()
         .Show();
     }
 }
 internal Row(Microsoft.Office.Interop.Word.Row _row, int _numberOfColumnsAccordingToTable, bool _applyHeadingStyle)
 {
     m_row = _row;
     m_numberOfColumnsAccordingToTable = _numberOfColumnsAccordingToTable;
     m_applyHeadingStyle = _applyHeadingStyle;
 }
Пример #29
0
        private void updatePlan(Dictionary <string, Object> keyValuePairs)
        {
            //
            Word.Application wordApp = new Word.Application();
            Word.Document    doc     = wordApp.Documents.Open(documentPathPlan, ReadOnly: false);
            try {
                doc.Activate();
                if (((string)(keyValuePairs["{id:kind}"])).Contains("Тренировк") || ((string)(keyValuePairs["{id:kind}"])).Contains("Самостояте") || ((string)(keyValuePairs["{id:kind}"])).Contains("Практическо"))
                {
                    int countQuestions = 0;
                    Dictionary <string, string> questions = (Dictionary <string, string>)(keyValuePairs["{id:questions}"]);
                    for (int e = 1; e <= doc.Paragraphs.Count; e++)
                    {
                        if (doc.Paragraphs[e].Range.Text.Contains("{id:adjunct}"))
                        {
                            FindAndReplace(wordApp, "{id:adjunct}", "ПРИЛОЖЕННИЯ");
                            Word.Paragraph p = doc.Paragraphs[e];
                            p.Range.InsertParagraphAfter();
                            p = doc.Paragraphs.Add(p.Range);
                            for (int i = 0; i < questions.Count; i++)
                            {
                                int a = i + 1;
                                p.Range.Text = "Карточка - задание на изучение " + a + "-го вопроса.^l";
                                p.Range.InsertParagraphAfter();
                                p = doc.Paragraphs.Add(p.Range);
                            }
                            for (int i = 0; i < questions.Count; i++)
                            {
                                int counter = doc.Paragraphs.Count - 5 + i;
                                doc.Paragraphs[counter].Range.InsertFile(Path.GetFullPath(Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, @"../../../../../Resources/AdditionalDocs/Spravochnik.docx")));
                                KeyValuePair <string, string> question = questions.ElementAt(i);
                                FindAndReplace(wordApp, "{id:questionName}", question.Key);
                                FindAndReplace(wordApp, "{id:countAjunct}", i + 1);
                                FindAndReplace(wordApp, "{id:questionDuration}", question.Value.Split(separator)[0]);
                                if (questions.Count > 1)
                                {
                                    countQuestions = 1;
                                    break;
                                }
                            }
                        }
                        //if(doc.Paragraphs[e].Range.Text.Trim().Replace("\r","").Replace("\a","").Replace("\n","").Equals("")&&countQuestions>0&&(countQuestions< questions.Count))
                        //{
                        //    doc.Paragraphs[e].Range.InsertFile(Path.GetFullPath(Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, @"../../../../../Resources/AdditionalDocs/Spravochnik.docx")));
                        //    KeyValuePair<string, string> question = questions.ElementAt(countQuestions);
                        //    FindAndReplace(wordApp, "{id:questionName}", question.Key);
                        //    FindAndReplace(wordApp, "{id:countAjunct}", countQuestions + 1);
                        //    FindAndReplace(wordApp, "{id:questionDuration}", question.Value);
                        //    countQuestions++;
                        //}
                        //int q = 1;
                    }
                }
                if (((string)(keyValuePairs["{id:kind}"])).ToLower().Contains("полувз") || ((string)(keyValuePairs["{id:kind}"])).ToLower().Contains("ПРО 3 ЧЕЛОВЕК СПРОСИТЬ КАК НАЗЫВАЕТСЯ"))
                {
                    foreach (Word.Paragraph paragraph in doc.Paragraphs)
                    {
                        if (paragraph.Range.Text.Contains("{id:image}"))
                        {
                            if (((string)(keyValuePairs["{id:kind}"])).ToLower().Contains("ПРО 3 ЧЕЛОВЕК СПРОСИТЬ КАК НАЗЫВАЕТСЯ"))
                            {
                                paragraph.Range.InsertFile(Path.GetFullPath(Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, @"../../../../../Resources/AdditionalDocs/image2.docx")));
                            }
                            else
                            {
                                paragraph.Range.InsertFile(Path.GetFullPath(Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, @"../../../../../Resources/AdditionalDocs/image1.docx")));
                            }
                        }
                    }
                }

                FindAndReplace(wordApp, "{id:image}", "");
                FindAndReplace(wordApp, "{id:adjunct}", "");
                FindAndReplace(wordApp, "{id:name}", keyValuePairs["{id:name}"]);
                FindAndReplace(wordApp, "{id:theme}", keyValuePairs["{id:theme}"]);
                FindAndReplace(wordApp, "{id:themeName}", keyValuePairs["{id:themeName}"]);
                FindAndReplace(wordApp, "{id:lesson}", keyValuePairs["{id:lesson}"]);
                FindAndReplace(wordApp, "{id:lessonName}", keyValuePairs["{id:lessonName}"]);
                FindAndReplace(wordApp, "{id:kind}", keyValuePairs["{id:kind}"]);
                FindAndReplace(wordApp, "{id:method}", keyValuePairs["{id:method}"]);
                FindAndReplace(wordApp, "{id:duration}", keyValuePairs["{id:duration}"]);
                FindAndReplace(wordApp, "{id:place}", keyValuePairs["{id:place}"]);

                string methodical = (string)keyValuePairs["{id:methodical}"];
                int    k          = 0;
                for (int i = 0; i < methodical.Length; i += 30)
                {
                    if (i > 0)
                    {
                        try
                        {
                            FindAndReplace(wordApp, "{id:methodical}", methodical.Substring(i + 1, 30) + "{id:methodical}");
                        }
                        catch (Exception e)
                        {
                            break;
                        }
                    }
                    else
                    {
                        FindAndReplace(wordApp, "{id:methodical}", methodical.Substring(i, 30) + "{id:methodical}");
                    }
                    k = i;
                }
                k += 30;
                FindAndReplace(wordApp, "{id:methodical}", methodical.Substring(k + 1));
                string literature = (string)keyValuePairs["{id:literature}"];
                int    l          = 0;
                for (int i = 0; i < literature.Length; i += 30)
                {
                    if (i > 0)
                    {
                        try
                        {
                            FindAndReplace(wordApp, "{id:literature}", literature.Substring(i + 1, 30) + "{id:literature}");
                        }
                        catch (Exception e)
                        {
                            break;
                        }
                    }
                    else
                    {
                        FindAndReplace(wordApp, "{id:literature}", literature.Substring(i, 30) + "{id:literature}");
                    }
                    l = i;
                }
                l += 30;
                FindAndReplace(wordApp, "{id:literature}", literature.Substring(l + 1));
                FindAndReplace(wordApp, "{id:technicalMeans}", keyValuePairs["{id:technicalMeans}"]);
                FindAndReplace(wordApp, "{id:intro}", keyValuePairs["{id:intro}"].ToString().Split(separator)[0]);
                FindAndReplace(wordApp, "{id:material}", keyValuePairs["{id:material}"]);
                FindAndReplace(wordApp, "{id:educationalQuestions}", keyValuePairs["{id:educationalQuestions}"]);
                FindAndReplace(wordApp, "{id:conclution}", keyValuePairs["{id:conclution}"].ToString().Split(separator)[0]);
                foreach (Word.Table table in doc.Tables)
                {
                    Word.Range rangeTable = table.Range;
                    foreach (Word.Row row in rangeTable.Rows)
                    {
                        foreach (Word.Cell cell in row.Cells)
                        {
                            Word.Range range = cell.Range;
                            if (range.Text.Contains("{id:questions}"))
                            {
                                FindAndReplace(wordApp, "{id:questions}", "");
                                Word.Row temporary = row;
                                int      count     = 1;
                                foreach (KeyValuePair <string, string> question in (Dictionary <string, string>)keyValuePairs["{id:questions}"])
                                {
                                    Object   oMissing = System.Reflection.Missing.Value;
                                    Word.Row newRow   = table.Rows.Add(ref oMissing);
                                    newRow.Cells[1].Range.Text = "2." + count;
                                    newRow.Cells[2].Range.Text = question.Key;
                                    newRow.Cells[3].Range.Text = question.Value.Split(separator)[0];
                                    Regex  regex        = new Regex("^ ?[1-9].*$");
                                    string questionFull = "";
                                    if (regex.IsMatch(question.Key))
                                    {
                                        questionFull = "Учебный вопрос. " + question.Key + " " + question.Value.Split(separator)[0] + "\r\n";
                                    }
                                    else
                                    {
                                        questionFull = "Учебный вопрос " + count + ". " + question.Key + " " + question.Value.Split(separator)[0] + "\r\n";
                                    }
                                    int r = 0;
                                    for (int e = 0; e < questionFull.Length; e += 30)
                                    {
                                        if (e > 0)
                                        {
                                            try
                                            {
                                                FindAndReplace(wordApp, "{id:questionOfLesson}", questionFull.Substring(e, 30) + "{id:questionOfLesson}");
                                            }
                                            catch (Exception q)
                                            {
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            FindAndReplace(wordApp, "{id:questionOfLesson}", questionFull.Substring(e, 30) + "{id:questionOfLesson}");
                                        }
                                        r = e;
                                    }
                                    r += 30;
                                    FindAndReplace(wordApp, "{id:questionOfLesson}", questionFull.Substring(r) + "{id:questionOfLesson}");
                                    temporary = newRow;
                                    count++;
                                }
                                Object   missing   = System.Reflection.Missing.Value;
                                Word.Row newRowENd = table.Rows.Add(ref missing);
                                newRowENd.Cells[1].Range.Text = "3";
                                newRowENd.Cells[2].Range.Text = "Заключение";
                                newRowENd.Cells[3].Range.Text = (string)keyValuePairs["{id:conclution}"].ToString().Split(separator)[0] + " мин";
                            }
                            else if (range.Text.Contains("{id:goal}"))
                            {
                                FindAndReplace(wordApp, "{id:goal}", "");
                                int count = 1;
                                foreach (string goal in (List <string>)keyValuePairs["{id:goal}"])
                                {
                                    Object   oMissing = System.Reflection.Missing.Value;
                                    Word.Row newRow   = table.Rows.Add(ref oMissing);
                                    newRow.Cells[1].Range.Text = count + "";
                                    newRow.Cells[2].Range.Text = goal;
                                    count++;
                                }
                            }
                        }
                    }
                }
                FindAndReplace(wordApp, "{id:questionOfLesson}", "");
                WordAPI.SaveFile(doc);
                WordAPI.Close(doc);
            }
            catch (Exception e)
            {
                doc.Close();
                new ExceptionWindow()
                .Show();
            }
        }
Пример #30
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var t = e.Argument as Tuple <string, string>;

            if (String.IsNullOrWhiteSpace(textBox1.Text))//вставить проверку, что указаны годы
            {
                MessageBox.Show("Не указан год рождения!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string select = @"SELECT Student.name, [Group].groupName, city.city, Student.street, Student.house, Student.flat, 
                                     Student.phone, Student.birth, sex.sex
                              FROM Student INNER JOIN
                              [Group] ON Student.idGroup = [Group].id INNER JOIN
                              city ON Student.id_city = city.id INNER JOIN
                              sex ON Student.id_sex = sex.id
                              WHERE (Student.birth LIKE '%" + t.Item1 + @"%') AND 
                                    (sex.sex = 'муж.') AND 
                                    (prikazNumKval = '') AND (prikazNumOut = '') 
                              ORDER BY name";

            DataSet ds1 = new DataSet();

            try
            {
                ds1 = Util.FillTable("Student", select);
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }

            if (ds1.Tables[0].Rows.Count == 0)
            {
                MessageBox.Show("С указанными данными никого нет!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Word.Application wdApp  = new Word.Application();
            Word.Document    wdDoc  = new Word.Document();
            Object           wdMiss = System.Reflection.Missing.Value;

            wdDoc = wdApp.Documents.Add(ref wdMiss, ref wdMiss, ref wdMiss, ref wdMiss);
            //wdApp.Visible = true; //сначала формируется документ, показывать потом
            wdDoc.PageSetup.LeftMargin   = 40;
            wdDoc.PageSetup.RightMargin  = 25;
            wdDoc.PageSetup.TopMargin    = 20;
            wdDoc.PageSetup.BottomMargin = 20;
            Word.Table tb;
            Word.Range _range;

            int columnsCount = 5;

            tb = wdDoc.Tables.Add(wdApp.Selection.Range, ds1.Tables[0].Rows.Count + 3, columnsCount);
            tb.Columns[1].Width = 40;
            tb.Rows[1].Height   = 40;
            tb.Columns[2].Width = 210;
            tb.Rows[2].Height   = 40;
            tb.Columns[3].Width = 60;
            tb.Rows[3].Height   = 40;
            tb.Columns[4].Width = 140;
            tb.Columns[5].Width = 90;

            Word.Row  row       = tb.Rows[1];
            Word.Cell firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }
            row       = tb.Rows[2];
            firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }

            tb.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wdApp.Selection.Range.Font.Name            = "Times New Roman";
            wdApp.Selection.Range.Font.Size            = 10;
            wdApp.Selection.Cells.VerticalAlignment    = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 0;

            tb.Cell(1, 1).Select();
            wdApp.Selection.Range.Font.Size = 14;
            wdApp.Selection.Font.Bold       = 1;
            tb.Cell(1, 1).Range.Text        = "Список";
            tb.Rows[2].Select();
            wdApp.Selection.Range.Font.Size = 12;
            wdApp.Selection.Font.Bold       = 1;
            tb.Cell(2, 1).Range.Text        = "юношей " + t.Item1 + " года рождения, подлежащих первоначальной постановке на воинский учет, обучающихся в  , по состоянию на " + t.Item2 + " года";

            tb.Rows[3].Select();
            wdApp.Selection.Font.Bold = 1;
            tb.Cell(3, 1).Range.Text  = "№ п/п";
            tb.Cell(3, 2).Range.Text  = "Фамилия, имя, отчество";
            tb.Cell(3, 3).Range.Text  = "№ курса, группа";
            tb.Cell(3, 4).Range.Text  = "Домашний адрес, телефон";
            tb.Cell(3, 5).Range.Text  = "Примечание";


            int rowCount  = 3;
            int rowNumber = 0;

            foreach (DataRow str in ds1.Tables[0].Rows)
            {
                rowCount++;
                rowNumber++;
                tb.Cell(rowCount, 1).Range.Text = rowNumber.ToString() + ".";
                tb.Cell(rowCount, 2).Range.Text = str.ItemArray[0].ToString();
                tb.Cell(rowCount, 3).Range.Text = Util.CalcKurs(str.ItemArray[1].ToString()) + " курс, гр. " + str.ItemArray[1].ToString(); //номер курса считать
                tb.Cell(rowCount, 4).Range.Text = "г." + str.ItemArray[2].ToString() + ", ул." + str.ItemArray[3].ToString() + ", д." +
                                                  str.ItemArray[4].ToString() + ", кв." + str.ItemArray[5].ToString() + ", т." +
                                                  str.ItemArray[6].ToString();
            }

            _range = wdDoc.Range(tb.Cell(4, 2).Range.Start, tb.Cell(rowCount, 5).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            _range = wdDoc.Range(tb.Cell(3, 1).Range.Start, tb.Cell(rowCount, columnsCount).Range.End);
            _range.Select();

            /* вызов макроса для отображения границ таблицы
             * Sub Сетка()
             * 'Сетка макрос
             * With Selection.Borders(wdBorderTop)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderLeft)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderBottom)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderRight)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderHorizontal)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderVertical)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * End Sub
             */
            try
            {
                wdApp.Run("Сетка");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " Сетка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            //нумерация страниц
            Word.Window activeWindow = wdDoc.Application.ActiveWindow;
            object      currentPage  = Word.WdFieldType.wdFieldPage;
            object      totalPages   = Word.WdFieldType.wdFieldNumPages;

            //переход к редактированию футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
            activeWindow.ActivePane.Selection.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            //напечатает номер страницы в формате X стр. из Y
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref currentPage, ref wdMiss, ref wdMiss);
            activeWindow.Selection.TypeText(" стр. из ");
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref totalPages, ref wdMiss, ref wdMiss);
            //выход из футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

            wdApp.Visible = true; //показать документ пользователю
        }
Пример #31
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var t = e.Argument as Tuple <string, string, string>;

            if (String.IsNullOrWhiteSpace(t.Item1) || String.IsNullOrWhiteSpace(t.Item2)) //вставить проверку, что указаны годы
            {
                MessageBox.Show("Не указаны годы рождения!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //здесь формирование ворд-документа
            string select = @"SELECT Student.name, Student.birth, district.district, Student.dateOut, sex.sex, Student.prichinaOut 
                              FROM Student INNER JOIN
                                   district ON Student.id_district = district.id INNER JOIN
                                   sex ON Student.id_sex = sex.id
                              WHERE ((prikazNumKval = '') AND (prikazNumOut != '')) AND
                                    (sex.sex = 'муж.') AND (Student.dateOut >= '" + t.Item3 + @"') AND (Student.id_goden = 1) AND 
                                    ((Student.id_city = 63) OR (Student.id_city = 64)) AND ((Student.birth >= '01.01." + t.Item1 + @"') AND (Student.birth <= '31.12." + birthTextBox2.Text + @"'))
                                    ORDER BY name";

            DataSet ds1 = new DataSet();

            try
            {
                ds1 = Util.FillTable("Student", select);
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }

            if (ds1.Tables[0].Rows.Count == 0)
            {
                MessageBox.Show("С указанными данными никого нет!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Word.Application wdApp  = new Word.Application();
            Word.Document    wdDoc  = new Word.Document();
            Object           wdMiss = System.Reflection.Missing.Value;

            wdDoc = wdApp.Documents.Add(ref wdMiss, ref wdMiss, ref wdMiss, ref wdMiss);
            //wdApp.Visible = true; //сначала формируется документ, показывать потом
            wdDoc.PageSetup.LeftMargin   = 40;
            wdDoc.PageSetup.RightMargin  = 25;
            wdDoc.PageSetup.TopMargin    = 20;
            wdDoc.PageSetup.BottomMargin = 20;
            Word.Table tb;
            Word.Range _range;

            int columnsCount = 6;

            tb = wdDoc.Tables.Add(wdApp.Selection.Range, ds1.Tables[0].Rows.Count + 3, columnsCount);
            tb.Columns[1].Width = 30;
            tb.Columns[2].Width = 200;
            tb.Columns[3].Width = 40;
            tb.Columns[4].Width = 140;
            tb.Columns[5].Width = 70;
            tb.Columns[6].Width = 70;

            tb.Rows[2].Height = 30;

            Word.Row  row       = tb.Rows[1];
            Word.Cell firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }
            row       = tb.Rows[2];
            firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }

            tb.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wdApp.Selection.Range.Font.Name            = "Times New Roman";
            wdApp.Selection.Range.Font.Size            = 10;
            wdApp.Selection.Cells.VerticalAlignment    = Word.WdCellVerticalAlignment.wdCellAlignVerticalTop;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 0;

            tb.Cell(1, 1).Select();
            wdApp.Selection.Range.Font.Size = 12;
            tb.Cell(1, 1).Range.Text        = "Список граждан, подлежащих призыву на военную службу и отчисленных из образовательных учреждений среднего профессионального образования по военному комиссариату Дзержинского и Калининского районов г.Новосибирска с " + t.Item3 + " года. \n";
            tb.Rows[2].Select();
            wdApp.Selection.Range.Font.Size           = 12;
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            tb.Cell(2, 1).Range.Text = " ";

            tb.Rows[3].Select();
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wdApp.Selection.Font.Bold = 1;
            tb.Cell(3, 1).Range.Text  = "№ п/п";
            tb.Cell(3, 2).Range.Text  = "Фамилия, имя, отчество";
            tb.Cell(3, 3).Range.Text  = "Год рожд.";
            tb.Cell(3, 4).Range.Text  = "Военный комиссариат";
            tb.Cell(3, 5).Range.Text  = "Дата отчисления";
            tb.Cell(3, 6).Range.Text  = "Примечание";

            int rowCount  = 3;
            int rowNumber = 0;

            foreach (DataRow str in ds1.Tables[0].Rows)
            {
                rowCount++;
                rowNumber++;
                tb.Cell(rowCount, 1).Range.Text = rowNumber.ToString() + ".";
                tb.Cell(rowCount, 2).Range.Text = str.ItemArray[0].ToString();
                tb.Cell(rowCount, 3).Range.Text = DateTime.Parse(str.ItemArray[1].ToString()).Year.ToString();
                tb.Cell(rowCount, 4).Range.Text = Voenkomat(str.ItemArray[2].ToString()); //вместо района пишется соответсвующий военкомат, если район не соответствует определенным то будет пусто
                tb.Cell(rowCount, 5).Range.Text = DateTime.Parse(str.ItemArray[3].ToString()).ToShortDateString();
                tb.Cell(rowCount, 6).Range.Text = str.ItemArray[5].ToString();
            }

            _range = wdDoc.Range(tb.Cell(4, 5).Range.Start, tb.Cell(rowCount, 5).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            _range = wdDoc.Range(tb.Cell(3, 1).Range.Start, tb.Cell(rowCount, columnsCount).Range.End);
            _range.Select();

            /* вызов макроса для отображения границ таблицы
             * Sub Сетка()
             * 'Сетка макрос
             * With Selection.Borders(wdBorderTop)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderLeft)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderBottom)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderRight)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderHorizontal)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderVertical)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * End Sub
             */
            try
            {
                wdApp.Run("Сетка");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " Сетка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }


            //таблица для подписей
            wdApp.Selection.EndOf(Word.WdUnits.wdStory);
            wdApp.Selection.InsertBreak(6);

            Word.Table tb2;
            tb2 = wdDoc.Tables.Add(wdApp.Selection.Range, 2, 4);

            tb2.Columns[1].Width = 40;
            tb2.Columns[2].Width = 180;
            tb2.Columns[3].Width = 180;

            tb2.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wdApp.Selection.Range.Font.Name            = "Times New Roman";
            wdApp.Selection.Range.Font.Size            = 12;
            wdApp.Selection.Cells.VerticalAlignment    = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 0;

            tb2.Rows[1].Select();
            tb2.Cell(1, 2).Range.Text = "Директор колледжа \n";
            tb2.Cell(1, 4).Range.Text = "  \n";

            tb2.Rows[2].Select();
            tb2.Cell(2, 2).Range.Text = " ";
            tb2.Cell(2, 3).Range.Text = " ";

            //нумерация страниц
            Word.Window activeWindow = wdDoc.Application.ActiveWindow;
            object      currentPage  = Word.WdFieldType.wdFieldPage;
            object      totalPages   = Word.WdFieldType.wdFieldNumPages;

            //переход к редактированию футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
            activeWindow.ActivePane.Selection.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            //напечатает номер страницы в формате X стр. из Y
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref currentPage, ref wdMiss, ref wdMiss);
            activeWindow.Selection.TypeText(" стр. из ");
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref totalPages, ref wdMiss, ref wdMiss);
            //выход из футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

            wdApp.Visible = true; //показать документ пользователю
        }