コード例 #1
0
        public void WriteLabel(Word.Table table, LabelTemplate template)
        {
            if (table == null)
            {
                return;
            }

            ActiveDocument.ActiveWindow.View.TableGridlines = true;

            Word.Range cellRange = table.Cell(1, 1).Range;

            cellRange.Delete();
            template.WriteToRange(cellRange);
            UpdateLabels();
        }
コード例 #2
0
ファイル: settings.cs プロジェクト: goffer14/WordAddin
        public static int BuildTable_ListOfEffctivePage(DocSettings DS, Word.Table tbl, int PageNum, int FirstHeaderPage)
        {
            int pagesSum = 1;

            PageNum = PageNum - FirstHeaderPage;
            int startPageNumber = PageNum;
            int RowToadd        = 0;

            while (pagesSum * 2 < PageNum)
            {
                if (settings.alert.worker.CancellationPending)
                {
                    return(-1);
                }
                RowToadd = (PageNum / 2) - pagesSum;
                if (PageNum % 2 != 0)
                {
                    RowToadd = RowToadd + 1;
                }

                tbl.Rows[tbl.Rows.Count].Select();
                DS.Doc.Application.Selection.InsertRowsBelow(RowToadd);
                pagesSum = tbl.Rows.Count - 2;
                PageNum  = DS.GetPageNumber() - FirstHeaderPage;
            }

            if (PageNum % 2 != 0)
            {
                tbl.Cell(tbl.Rows.Count, 5).Range.Text = "x";
                tbl.Cell(tbl.Rows.Count, 6).Range.Text = "x";
                tbl.Cell(tbl.Rows.Count, 7).Range.Text = "x";
                tbl.Cell(tbl.Rows.Count, 8).Range.Text = "x";
            }

            return(PageNum - startPageNumber);
        }
コード例 #3
0
        private void ExporterObjects_Paragraph(ref Document document, System.Data.DataTable datatable, string namePara)
        {
            try
            {
                object missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Paragraph para = document.Content.Paragraphs.Add(ref missing);
                para.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                para.Range.Font.Bold  = 1;
                para.Range.Font.Size  = 16;
                para.Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlack;
                para.Range.Text       = "\n" + namePara;
                para.Range.InsertParagraphAfter();


                para.Range.Font.Bold  = 1;
                para.Range.Font.Size  = 14;
                para.Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlack;
                para.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                if (datatable.Rows.Count > 0)
                {
                    Microsoft.Office.Interop.Word.Table firstTable = document.Tables.Add(para.Range, datatable.Rows.Count, datatable.Columns.Count, ref missing, ref missing);
                    firstTable.Borders.Enable        = 1;
                    firstTable.Cell(1, 1).Range.Text = "Biển số";
                    firstTable.Cell(1, 2).Range.Text = "Thời gian thanh toán";
                    firstTable.Cell(1, 3).Range.Text = "Tiền trả" + " (VNĐ)";
                    Object beforeRow = Type.Missing;

                    para.Range.Font.Bold  = 0;
                    para.Range.Font.Size  = 14;
                    para.Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlack;
                    para.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;


                    for (int i = 0; i < datatable.Rows.Count; i++)
                    {
                        firstTable.Rows.Add(ref beforeRow);
                        firstTable.Cell(i + 2, 1).Range.Text = datatable.Rows[i][0].ToString();
                        firstTable.Cell(i + 2, 2).Range.Text = datatable.Rows[i][1].ToString();
                        firstTable.Cell(i + 2, 3).Range.Text = datatable.Rows[i][2].ToString();
                    }
                }
                else
                {
                    Microsoft.Office.Interop.Word.Table firstTable = document.Tables.Add(para.Range, 1, datatable.Columns.Count, ref missing, ref missing);
                    firstTable.Borders.Enable        = 1;
                    firstTable.Cell(1, 1).Range.Text = "Biển số";
                    firstTable.Cell(1, 2).Range.Text = "Thời gian thanh toán";
                    firstTable.Cell(1, 3).Range.Text = "Tiền trả" + " (VNĐ)";
                    Object beforeRow = Type.Missing;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(" Err " + ex.Message);
            }
        }
コード例 #4
0
 //Step 2
 public void SearchDateCell(string day)
 {
     for (int i = 1; i < tbl.Rows.Count; i++)
     {
         for (int j = 1; j < 2; j++)
         {
             string row = tbl.Cell(i, j).Range.Text;
             row = row.Replace("\r\a", "");
             if (day == row)
             {
                 CellWithCheldue(1, 1, 1);
             }
         }
     }
 }
コード例 #5
0
        /* public static void GetGuidelineFromTable(ref List<string> guidelineTable, Word.Table table)
         * {
         *
         *   for (int row = 1; row <= table.Rows.Count; row++)
         *   {
         *       var cell = table.Cell(row, 1);
         *       var text = cell.Range.Text;
         *       if (text.Contains("Guidelines"))
         *       {
         *           guidelineTable.Add(text);
         *       }
         *       // text now contains the content of the cell.
         *   }
         *
         * }*/


        public static void GetGuidelinesInTable(ref List <Guideline> guidelines, int chapterNumber, Word.Table table, ExtractionMode extractionMode)
        {
            Word.Range individualGuidelineRange;
            for (int row = 1; row <= table.Rows.Count; row++)
            {
                var cell = table.Cell(row, 1);
                var text = cell.Range.Text;
                if (text.Contains("Guidelines"))
                {
                    individualGuidelineRange = cell.Range;

                    ParseIndividualGuidelinesInTable(cell.Range, ref guidelines, chapterNumber, extractionMode);
                }
            }
        }
コード例 #6
0
ファイル: WordUltil.cs プロジェクト: longct/PPM_IFC
        public void WriteTable(DataTable vDataTable, int vIndexTable)
        {
            Word.Table tbl    = _doc.Tables[vIndexTable];
            int        lenrow = vDataTable.Rows.Count;
            int        lencol = vDataTable.Columns.Count;

            for (int i = 0; i < lenrow; ++i)
            {
                object ob = System.Reflection.Missing.Value;
                tbl.Rows.Add(ref ob);
                for (int j = 0; j < lencol; ++j)
                {
                    tbl.Cell(i + 2, j + 1).Range.Text = vDataTable.Rows[i][j].ToString();
                }
            }
        }
コード例 #7
0
        private void button5_Click(object sender, EventArgs e)
        {
            Word.Document WordDoc;
            var           WordApp = new Word.Application();

            WordApp.Visible = true;
            //object template = Type.Missing;
            //object newTemplate = false;
            //object documentType = Word.WdNewDocumentType.wdNewBlankDocument;
            //object visible = true;
            WordDoc = WordApp.Documents.Add(Type.Missing, false, Word.WdNewDocumentType.wdNewBlankDocument, true);
            //object start = 0;
            //object end = 0;
            Word.Range wordrange            = WordDoc.Range(0, 0);
            object     defaultTableBehavior = Word.WdDefaultTableBehavior.wdWord9TableBehavior;
            object     autoFitBehavior      = Word.WdAutoFitBehavior.wdAutoFitWindow;

            Word.Table wordtable = WordDoc.Tables.Add(wordrange, dataGridView1.RowCount, dataGridView1.ColumnCount, ref defaultTableBehavior, ref autoFitBehavior);

            Word.Range wordcellrange = WordDoc.Tables[1].Cell(1, 1).Range;
            wordcellrange.Text = "№";
            wordcellrange      = wordtable.Cell(1, 2).Range;
            wordcellrange.Text = "Фамилия";
            wordcellrange      = wordtable.Cell(1, 3).Range;
            wordcellrange.Text = "Имя";
            wordcellrange      = wordtable.Cell(1, 4).Range;
            wordcellrange.Text = "Отчество";
            wordcellrange      = wordtable.Cell(1, 5).Range;
            wordcellrange.Text = "Должность";
            wordcellrange      = wordtable.Cell(1, 6).Range;
            wordcellrange.Text = "Дата рождения";
            wordcellrange      = wordtable.Cell(1, 7).Range;
            wordcellrange.Text = "Дата приема на работу";
            wordcellrange      = wordtable.Cell(1, 8).Range;
            wordcellrange.Text = "Номер кабинета";

            for (int m = 1; m < wordtable.Rows.Count; m++)
            {
                for (int n = 0; n < wordtable.Columns.Count; n++)
                {
                    wordcellrange      = wordtable.Cell(m + 1, n + 1).Range;
                    wordcellrange.Text = dataGridView1[n, m - 1].Value.ToString();
                }
            }
        }
コード例 #8
0
        public void CargaTablaTitulo(objWord.Document objDocumento, string titulo, string variable)
        {
            object oMissing  = System.Reflection.Missing.Value;
            object oEndOfDoc = "\\endofdoc";

            objWord.Range wrdRng = objDocumento.Bookmarks.get_Item(ref oEndOfDoc).Range;

            objWord.Table Otable = objDocumento.Tables.Add(wrdRng, 1, 1, ref oMissing, ref oMissing);

            Otable.Borders[objWord.WdBorderType.wdBorderLeft].Visible   = true;
            Otable.Borders[objWord.WdBorderType.wdBorderRight].Visible  = true;
            Otable.Borders[objWord.WdBorderType.wdBorderTop].Visible    = true;
            Otable.Borders[objWord.WdBorderType.wdBorderBottom].Visible = true;
            Otable.Cell(1, 1).Range.Text = titulo + "" + variable;
            Otable.Range.Bold            = 12; Otable.Range.Font.Size = 15;
        }
コード例 #9
0
 public void itmtoword(pswift.IItem itm, Word.Table tbl, int rowidx, string tp)
 {
     if (rowidx > 20)
     {
         tbl.Rows.Add(System.Reflection.Missing.Value);
     }
     if (tp == "Digitizer")
     {
         tbl.Cell(rowidx, 1).Range.Font.Bold   = 1;
         tbl.Cell(rowidx, 1).Range.Font.Italic = 0;
     }
     else
     {
         tbl.Cell(rowidx, 1).Range.Font.Bold   = 0;
         tbl.Cell(rowidx, 1).Range.Font.Italic = 1;
     }
     tbl.Cell(rowidx, 1).Range.Text = itm.Name;
     tbl.Cell(rowidx, 2).Range.Text = itm.GetPropertyResultAsString("Qty", "");
     tbl.Cell(rowidx, 3).Range.Text = itm.GetProperty("Qty").Units;
     tbl.Cell(rowidx, 4).Range.Text = itm.GetPropertyResultAsString("Price Each", "");
     tbl.Cell(rowidx, 5).Range.Text = itm.GetPropertyResultAsString("Price Total", "");
 }
コード例 #10
0
        void AddOELogTable(string newFile)
        {
            try
            {
                Word.Application Wapp = new Word.Application();
                Wapp.Visible = false;
                Word.Document doc = Wapp.Documents.Open(newFile);


                //AddPersonnelAndInitiationTable();
                //AddEnvironmentAndAssumptionsTable();
                //AddStepsTable();
                //AddScreenshotsTable();


                object     Missing  = System.Reflection.Missing.Value;
                object     EndOfDoc = "\\endofdoc";
                Word.Range Range    = doc.Bookmarks.get_Item(ref EndOfDoc).Range;
                object     objBreak = Word.WdBreakType.wdPageBreak;
                object     objUnit  = Word.WdUnits.wdStory;
                Wapp.Selection.EndKey(ref objUnit, ref Missing);
                Wapp.Selection.InsertBreak(ref objBreak);
                Word.Paragraph objP = doc.Paragraphs.Add();
                objP.Range.Bold = 1;

                doc.Tables.Add(Range, 1, 6, Missing, Missing);
                Word.Table stepTable = doc.Tables[1];
                stepTable.Borders.Enable  = 1;
                stepTable.Range.Font.Size = 11;
                stepTable.Range.Font.Name = "Times New Roman";

                stepTable.Rows[1].Range.Bold    = 1;
                stepTable.Cell(1, 1).Range.Text = "Step #";
                stepTable.Cell(1, 2).Range.Text = "Req ID";
                stepTable.Cell(1, 3).Range.Text = "Action(s)";
                stepTable.Cell(1, 4).Range.Text = "Expected Result(s)";
                stepTable.Cell(1, 5).Range.Text = "Actual Result";
                stepTable.Cell(1, 6).Range.Text = "Comments";

                Range = null;
                Range = doc.Bookmarks.get_Item(EndOfDoc).Range;
                Word.Paragraph objPara2 = doc.Content.Paragraphs.Add(Range);
                objPara2.Range.InsertParagraphBefore();

                doc.Tables.Add(Range, 1, 1, Missing, Missing);
                Word.Table screenshotTable = doc.Tables[2];

                doc.Close();
                Wapp.Quit();
            }
            catch (Exception e)
            {
            }
        }
コード例 #11
0
        private void BookmarkInsertCrossReference()
        {
            Word.Document    doc = Globals.ThisAddIn.Application.ActiveDocument;
            Word.Application app = Globals.ThisAddIn.Application;

            int i = 0;

            ArrayList refsToSave = new ArrayList();

            foreach (Word.Paragraph paragraph in doc.Paragraphs)
            {
                Word.Style style     = paragraph.get_Style() as Word.Style;
                string     styleName = style.NameLocal;

                if (styleName == "Heading 1,2016_Überschrift 1,Headline 1")
                {
                    i++;
                }
                else if (styleName == "Heading 2,2016_Überschrift 2,Headline 2")
                {
                    i++;
                }
                else if (styleName == "Heading 3,2016_Überschrift 3,Headline 3")
                {
                    i++;
                    refsToSave.Add(i);
                }
            }

            Word.Table table = FindTable("Report Name");

            foreach (int j in refsToSave)
            {
                table.Rows.Add();

                table.Cell(table.Rows.Count, 1).Range.Select();
                insertCrossReference(app, Word.WdReferenceKind.wdContentText, j);

                //table.Cell(table.Rows.Count, 4).Range.Select();
                //table.Cell(table.Rows.Count, 4).Range.Delete();
                //insertCrossReference(app, Word.WdReferenceKind.wdPageNumber, j);
            }
        }
コード例 #12
0
 private void Filliing_1(Word.Table wordtable1) ///заполнение первой таблицы
 {
     Word.Range wordcellrange;
     wordcellrange      = wordtable1.Cell(1, 1).Range;
     wordcellrange.Text = "Эi";
     wordcellrange      = wordtable1.Cell(1, 2).Range;
     wordcellrange.Text = "ri";
     wordcellrange      = wordtable1.Cell(1, 3).Range;
     wordcellrange.Text = "DRi";
     for (int i = 0; i < wordtable1.Rows.Count; i++)
     {
         for (int j = 0; j < wordtable1.Columns.Count; j++)
         {
             if (i == 0 && j > 2)
             {
                 wordcellrange      = wordtable1.Cell(i + 1, j + 1).Range;
                 wordcellrange.Text = "В" + (j - 2);
             }
             if (i != 0)
             {
                 if (j < 3)
                 {
                     wordcellrange      = wordtable1.Cell(i + 1, j + 1).Range;
                     wordcellrange.Text = option_table[i - 1].expert;
                     j++;
                     wordcellrange      = wordtable1.Cell(i + 1, j + 1).Range;
                     wordcellrange.Text = option_table[i - 1].expert_rj;
                     j++;
                     wordcellrange      = wordtable1.Cell(i + 1, j + 1).Range;
                     wordcellrange.Text = option_table[i - 1].expert_Drj;
                 }
                 else
                 {
                     wordcellrange      = wordtable1.Cell(i + 1, j + 1).Range;
                     wordcellrange.Text = option_table[i - 1].Marks[j - 3];
                 }
             }
         }
     }
 }
コード例 #13
0
        //</Snippet82>


        //---------------------------------------------------------------------
        //<Snippet89>
        private void CreateDocumentPropertyTable()
        {
            //<Snippet90>
            object start = 0, end = 0;

            Word.Document document = this.Application.ActiveDocument;
            Word.Range    rng      = document.Range(ref start, ref end);
            //</Snippet90>

            // Insert a title for the table and paragraph marks.
            //<Snippet91>
            rng.InsertBefore("Document Statistics");
            rng.Font.Name = "Verdana";
            rng.Font.Size = 16;
            rng.InsertParagraphAfter();
            rng.InsertParagraphAfter();
            rng.SetRange(rng.End, rng.End);
            //</Snippet91>

            // Add the table.
            //<Snippet92>
            rng.Tables.Add(document.Paragraphs[2].Range, 3, 2, ref missing, ref missing);
            //</Snippet92>

            // Format the table and apply a style.
            //<Snippet93>
            Word.Table tbl = document.Tables[1];
            tbl.Range.Font.Size = 12;
            tbl.Columns.DistributeWidth();

            object styleName = "Table Professional";

            tbl.set_Style(ref styleName);
            //</Snippet93>

            // Insert document properties into cells.
            //<Snippet94>
            tbl.Cell(1, 1).Range.Text = "Document Property";
            tbl.Cell(1, 2).Range.Text = "Value";

            tbl.Cell(2, 1).Range.Text = "Subject";
            tbl.Cell(2, 2).Range.Text = ((Office.DocumentProperties)(document.BuiltInDocumentProperties))
                                        [Word.WdBuiltInProperty.wdPropertySubject].Value.ToString();

            tbl.Cell(3, 1).Range.Text = "Author";
            tbl.Cell(3, 2).Range.Text = ((Office.DocumentProperties)(document.BuiltInDocumentProperties))
                                        [Word.WdBuiltInProperty.wdPropertyAuthor].Value.ToString();
            //</Snippet94>
        }
コード例 #14
0
        public void insertperidword(string bookmark1, System.Data.DataTable dt)  //老炼周期表格的插入
        {
            object oStart1 = bookmark1;

            wordApp.ActiveDocument.Bookmarks.get_Item(ref oStart1).Select();
            if (dt.Rows.Count != 0)
            {
                wordApp.Selection.InsertRowsBelow(dt.Rows.Count);
            }
            wordApp.ActiveDocument.Bookmarks.get_Item(ref oStart1).Select();
            int b = (int)(wordApp.Selection.get_Information(WdInformation.wdEndOfRangeRowNumber));

            Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[1];
            System.Data.DataTable dtcut = dt.Copy();
            dtcut.Columns.Remove("剩余时间");
            for (int i = 0; i < dtcut.Columns.Count; i++)
            {
                for (int j = 0; j < dtcut.Rows.Count; j++)
                {
                    table.Cell(j + b + 1, i + 1).Range.Text = dtcut.Rows[j][i].ToString();
                }
            }

            int tempflag = 0;

            for (int i = 0; i < dtcut.Rows.Count - 1; i++)
            {
                string str1 = table.Cell(i + b + 1, 0).Range.Text.ToString();
                for (int j = i + 1; j < dtcut.Rows.Count; j++)
                {
                    string str2 = table.Cell(j + b + 1, 0).Range.Text.ToString();
                    if (str1 == str2)
                    {
                        tempflag = j;
                    }
                    else
                    {
                        break;
                    }
                }
                for (int k = i; k < tempflag; k++)
                {
                    table.Cell(k + b + 1, 0).Range.Text = "";
                }
                table.Cell(i + b + 1, 0).Merge(table.Cell(tempflag + b + 1, 0));
                i = tempflag;
            }
        }
コード例 #15
0
ファイル: WordHelper.cs プロジェクト: soon14/ColPlanning
        /// <summary>
        /// 按照格式插入表格
        /// </summary>
        /// <param name="n"></param>
        /// <param name="row"></param>
        /// <param name="columns"></param>
        /// <param name="values"></param>
        /// <param name="pFontSize"></param>
        /// <param name="pFontBold"></param>
        public void InsertCellFormat(int n, int row, int columns, string[] values, int pFontSize, int pFontBold)
        {
            Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
            //  table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
            try
            {
                for (int i = 0; i < columns; i++)
                {
                    //table.Cell(row, i + 1).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                    //table.Cell(row, i + 1).Range.Font.Size = pFontSize;
                    //table.Cell(row, i + 1).Range.Font.Bold = pFontBold;
                    table.Cell(row, i + 1).Range.Text = values[i];

                    // table.Cell(row, i + 1).Range.Font.Color 设置字体颜色
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString(), "提示!");
            }
        }
コード例 #16
0
ファイル: WordWriter.cs プロジェクト: adsisplus/TyrsaSystem
        public void CreateTableByTag(List <string[]> tableData, string tag)
        {
            int cols = 5;
            var contentTablaMateriales = Document.SelectContentControlsByTag(tag);

            Word.Range firstRange = contentTablaMateriales[1].Range;
            Word.Table table      = Document.Tables.Add(firstRange, tableData.Count, cols);
            float      padding    = 3;

            for (int iRow = 1; iRow <= tableData.Count; iRow++)
            {
                for (int iCol = 1; iCol <= cols; iCol++)
                {
                    Word.Cell cell = table.Cell(iRow, iCol);
                    if (iRow == 1)
                    {
                        cell.Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray125;
                        cell.Range.Bold = 3;
                    }
                    if (iCol != cols)
                    {
                        cell.Width = 50f;
                        cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    }
                    else
                    {
                        cell.Width = 300f;
                        cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify;
                    }

                    cell.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleOutset;
                    cell.TopPadding    = padding;
                    cell.LeftPadding   = padding;
                    cell.RightPadding  = padding;
                    cell.BottomPadding = padding;
                    string cellValue = tableData[iRow - 1][iCol - 1];
                    cell.Range.Text = cellValue;
                }
            }
        }
コード例 #17
0
        public void insertrow(string bookmark1, System.Data.DataTable dt)
        {
            object oStart1 = bookmark1;

            wordApp.ActiveDocument.Bookmarks.get_Item(ref oStart1).Select();
            if (dt.Rows.Count != 0)
            {
                wordApp.Selection.InsertRowsBelow(dt.Rows.Count);
            }
            wordApp.ActiveDocument.Bookmarks.get_Item(ref oStart1).Select();
            int b = (int)(wordApp.Selection.get_Information(WdInformation.wdEndOfRangeRowNumber));

            Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[1];
            System.Data.DataTable dtcut = dt.Copy();
            dtcut.Columns.Remove("资源测试通道");
            for (int i = 0; i < dtcut.Columns.Count; i++)
            {
                for (int j = 0; j < dtcut.Rows.Count; j++)
                {
                    table.Cell(j + b + 1, 1).Range.Text     = (j + 1).ToString();
                    table.Cell(j + b + 1, i + 2).Range.Text = dtcut.Rows[j][i].ToString();
                }
            }


            if (bookmark1 == "IOOut" || bookmark1 == "IOIn" || bookmark1 == "DA" || bookmark1 == "AD")
            {
                for (int i = 0; i < dtcut.Columns.Count - 1; i++)
                {
                    for (int j = 0; j < dtcut.Rows.Count; j = j + 2)
                    {
                        string str1 = table.Cell(j + b + 1, i + 2).Range.Text.ToString();
                        string str2 = table.Cell(j + b + 2, i + 2).Range.Text.ToString();
                        if (str1 == str2)
                        {
                            table.Cell(j + b + 1, i + 2).Range.Text = "";
                            table.Cell(j + b + 1, i + 2).Merge(table.Cell(j + b + 2, i + 2));
                        }
                    }
                }
            }
        }
コード例 #18
0
        /// <summary>
        /// Function to fill a table with riskReducingMeasures from the database.
        /// </summary>
        /// <param name="document">Document instance where the table can be found.</param>
        /// <param name="table">Table instance of the table to add values to.</param>
        /// <param name="dataRows">A DataView representing the data to be inserted into the table.</param>
        /// <param name="displayColumn">A Column name in the DataView representing which column to display in the table.</param>
        /// <param name="checkBoxSelectionColumn">A Column name in the DataView representing a column to check for for adding checkboxes in the table.</param>
        public void fillTableWithRiskReducingMeasures(Document document, Microsoft.Office.Interop.Word.Table table, DataView dataRows, string displayColumn, string checkBoxSelectionColumn = "")
        {
            if (table != null)
            {
                try
                {
                    for (int i = 0; i < dataRows.Count; i++)
                    {
                        //Add row if we are at the end of the table.
                        if (i % table.Columns.Count == 0)
                        {
                            table.Rows.Add(missing);
                        }

                        //Get cell so we can add stuff to it.
                        Range cell = table.Cell(table.Rows.Count - 1, (i % table.Columns.Count) + 1).Range;
                        cell.Text = dataRows[i][displayColumn].ToString();
                        cell.Select();

                        //If we have a column to add a checkbox, add a checkbox.
                        if (checkBoxSelectionColumn != "")
                        {
                            if (dataRows[i][checkBoxSelectionColumn].ToString() == "1")
                            {
                                cell.Collapse(ref missing);
                                FormField checkBox = cell.FormFields.Add(cell, WdFieldType.wdFieldFormCheckBox);
                                checkBox.CheckBox.Value = true;
                                checkBox = null;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            }
        }
コード例 #19
0
        public void KoeffDuplex(Dictionary <double, List <double> > dict, Word.Table oTable)
        {
            int i = 2;

            for (int k = 0; k < dict.Keys.Count; k++)
            {
                int           m        = 0;
                double        alg_2_5d = 0;
                double        alg_2_5  = 0;
                double        alg_2_6d = 0;
                double        alg_2_6  = 0;
                List <double> list_Keap;
                dict.TryGetValue(dict.Keys.ElementAt(k), out list_Keap);
                for (int j = 0; j < list_Keap.Count; j += 4)
                {
                    alg_2_5d += list_Keap[j];
                    alg_2_5  += list_Keap[j + 1];
                    alg_2_6d += list_Keap[j + 2];
                    alg_2_6  += list_Keap[j + 3];
                    m++;
                }

                alg_2_5d = alg_2_5d / m;
                alg_2_5  = alg_2_5 / m;
                alg_2_6d = alg_2_6d / m;
                alg_2_6  = alg_2_6 / m;

                oTable.Rows.Add();
                oTable.Cell(i, 1).Range.Text = dict.Keys.ElementAt(k).ToString();
                oTable.Cell(i, 2).Range.Text = alg_2_5d.ToString("N2");
                oTable.Cell(i, 3).Range.Text = alg_2_5.ToString("N2");
                oTable.Cell(i, 4).Range.Text = alg_2_6d.ToString("N2");
                oTable.Cell(i, 5).Range.Text = alg_2_6.ToString("N2");
                oTable.Cell(i, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                oTable.Cell(i, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

                i++;
            }
            oTable.Rows[i].Delete();
        }
コード例 #20
0
        private void print(DataGridView ExportDgrid, Microsoft.Office.Interop.Word._Document doc, String flag)
        {
            int row = ExportDgrid.RowCount;
            int column = ExportDgrid.ColumnCount;
            int i, j;

            Microsoft.Office.Interop.Word.Table table = doc.Tables.Add(wordApp.Selection.Range, row + 1, column, NoThing, NoThing);

            table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;

            if (column == 4)
            {
                table.Columns[1].Width = 80;
                table.Columns[3].Width = 80;
                table.Cell(2, 2).Merge(table.Cell(2, column));
            }
            else
            {
                table.Columns[1].Width = 80;
                table.Columns[2].Width = 80;
            }
            table.Cell(1, 1).Merge(table.Cell(1, column));

            try
            {
                table.Cell(1, 1).Range.Text    = flag;
                table.Rows[1].Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlue;
                for (i = 0; i < row; i++)
                {
                    for (j = 0; j < column; j++)
                    {
                        if (ExportDgrid.Rows[i].Cells[j].Value != null)
                        {
                            table.Cell(i + 2, j + 1).Range.Text = ExportDgrid.Rows[i].Cells[j].Value.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
コード例 #21
0
        private void Button_ClickDownload(object sender, RoutedEventArgs e)
        {
            var wordApp = new Word.Application();

            wordApp.Visible = false;
            var wordDocument = wordApp.Documents.Add(FileName);

            var num    = Convert.ToInt32((sender as Button).Uid);
            var Client = db.Clients.Where(c => c.ClientNum == CNum).FirstOrDefault();
            var sum    = db.Orders.Where(o => o.OrderNum == num).FirstOrDefault();
            var count  = db.OrderDetails.Where(o => o.OrderNum == num).Count();

            ReplaceWord("{OrderNum}", (sender as Button).Uid.ToString(), wordDocument);
            ReplaceWord("{surname}", Client.Surname, wordDocument);
            ReplaceWord("{name}", Client.Name, wordDocument);
            ReplaceWord("{patronymic}", Client.Patronymic, wordDocument);
            ReplaceWord("{sum}", sum.Sum.ToString(), wordDocument);
            var date = sum.FirstDate.Date.ToString("dd/MM/yyyy");

            ReplaceWord("{date}", date, wordDocument);

            Word.Table tab  = wordDocument.Tables[1];
            int        i    = 2;
            var        rows = 0;

            foreach (OrderDetails o in db.OrderDetails.Where(o => o.OrderNum == num))
            {
                rows++;
            }

            foreach (OrderDetails o in db.OrderDetails.Where(o => o.OrderNum == num))
            {
                tab.Rows.Add();
                tab.Cell(i, 1).Range.Text = (i - 1).ToString();
                tab.Cell(i, 2).Range.Text = o.ProductNum.ToString();
                var prod = db.Products.Where(p => p.ProductNum == o.ProductNum).FirstOrDefault();
                tab.Cell(i, 3).Range.Text = prod.Name;
                tab.Cell(i, 4).Range.Text = o.Cost.ToString();
                tab.Cell(i, 5).Range.Text = o.Quantity.ToString();
                tab.Cell(i, 6).Range.Text = (o.Cost * o.Quantity).ToString();
                i++;
            }
            wordApp.Visible = true;
        }
コード例 #22
0
ファイル: Word.cs プロジェクト: Zagii/EAkzg
        public Wordy.Table wstawTabele(object bookmark, String[] naglowki)
        {
            Wordy.Bookmark book = doc.Bookmarks.get_Item(ref oEndOfDoc);

            Wordy.Table tab = doc.Tables.Add(book.Range, 1, naglowki.Count());
            //  tab.Range.ParagraphFormat.SpaceAfter = 6;

            object styleName = stylTab;

            tab.set_Style(ref styleName);

            int i = 1;

            foreach (String kol in naglowki)
            {
                Wordy.Cell cel = tab.Cell(1, i);
                cel.Range.Text = kol;
                object snorm = stylNorm;
                cel.Range.set_Style(ref snorm);
                i++;
            }

            return(tab);
        }
コード例 #23
0
ファイル: ReportFromTemplate.cs プロジェクト: yeahZL/Yahaha
        public void InsertPicures(Microsoft.Office.Interop.Word.Table table, int row, int column, string value,
                                  object count, int i, float width = 184.56f, float height = 184.56f)
        {
            //row和column表示行列数,需要设置成上一行的最后一列
            //value表示图片绝对路径
            //count表示从上一行的最后一列开始,到本行本列的最后一个字符的个数。。。。。。。
            //i表示本文档的第i个图片
            //wdith和height表示宽和高
            //1cm=28.35px
            table.Cell(row, column).Select();

            object miss = System.Reflection.Missing.Value;
            object unit = Microsoft.Office.Interop.Word.WdUnits.wdCharacter; //切换字符;

            wordApp.Selection.MoveRight(ref unit, ref count, ref miss);      //移动焦点

            object LinkToFile1       = false;
            object SaveWithDocument1 = true;
            object Anchor1           = wordDoc.Application.Selection.Range;

            wordDoc.InlineShapes.AddPicture(value, ref LinkToFile1, ref SaveWithDocument1, ref Anchor1);
            wordDoc.InlineShapes[i].Width = width;                              //图片宽度
            wordDoc.Application.ActiveDocument.InlineShapes[i].Height = height; //图片高度
        }
コード例 #24
0
ファイル: MainWindow.xaml.cs プロジェクト: LizzVs/Beauty
        private void buttonWord_Click(object sender, RoutedEventArgs e)
        {
            var application = new Word.Application();

            Word.Document doc = application.Documents.Add();

            Word.Paragraph tableParagraph = doc.Paragraphs.Add();
            Word.Range     tableRange     = tableParagraph.Range;
            Word.Table     prodTable      = doc.Tables.Add(tableRange, Products.Rows.Count + 1, 3);
            prodTable.Borders.InsideLineStyle             = prodTable.Borders.OutsideLineStyle
                                                          = Word.WdLineStyle.wdLineStyleSingle;
            prodTable.Range.Cells.VerticalAlignment       = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            Word.Range cellRange;
            cellRange      = prodTable.Cell(1, 1).Range;
            cellRange.Text = "id";
            cellRange      = prodTable.Cell(1, 2).Range;
            cellRange.Text = "Название товара";
            cellRange      = prodTable.Cell(1, 3).Range;
            cellRange.Text = "Стоимость";

            /*    cellRange = champTable.Cell(1, 4).Range;
             *  cellRange.Text = "Место проведения";
             *  cellRange = champTable.Cell(1, 5).Range;
             *  cellRange.Text = "Начало";
             *  cellRange = champTable.Cell(1, 6).Range;
             *  cellRange.Text = "Конец";*/

            prodTable.Rows[1].Range.Bold = 1;
            for (int i = 0; i < Products.Rows.Count; i++)
            {
                cellRange      = prodTable.Cell(i + 2, 1).Range;
                cellRange.Text = Products.Rows[i]["id"].ToString();
                cellRange      = prodTable.Cell(i + 2, 2).Range;
                cellRange.Text = Products.Rows[i]["title"].ToString();
                cellRange      = prodTable.Cell(i + 2, 3).Range;
                cellRange.Text = Products.Rows[i]["cost"].ToString();;
            }

            application.Visible = true;

            doc.SaveAs2(Directory.GetCurrentDirectory() + @"Products.docx");
            doc.Close();
        }
コード例 #25
0
ファイル: UCUser.cs プロジェクト: sisca-guillemot-m2l/FREDI
        private void button1_Click(object sender, EventArgs e)
        {
            getContent returnInfo             = new getContent();
            MySqlConnectionStringBuilder conn = new MySqlConnectionStringBuilder();

            conn.Server   = returnInfo.getServer();
            conn.UserID   = returnInfo.getId();
            conn.Password = returnInfo.getPassword();
            conn.Database = returnInfo.getDb();
            var             connString = conn.ToString();
            MySqlConnection coInsert   = new MySqlConnection(connString);

            coInsert.Open();
            object save13   = mainPathUser + @"\bordereauFillDataGridUser.docx";
            string template = mainPathUser + @"\templateBasic.docx";
            object missing  = Missing.Value;

            word.Application wordApp = new word.Application();
            wordApp.Visible = true;
            word.Document document = wordApp.Documents.OpenNoRepairDialog(template);
            document.Activate();
            word.Table table = document.Tables[1];
            for (int a = comptSlip - 1; a >= 0; a--)
            {
                table.Cell(1, 1).Range.Text = dataGridView1.Rows[a].Cells[1].Value.ToString();
                table.Cell(1, 2).Range.Text = dataGridView1.Rows[a].Cells[2].Value.ToString();
                table.Cell(1, 3).Range.Text = dataGridView1.Rows[a].Cells[3].Value.ToString();
                table.Cell(1, 4).Range.Text = dataGridView1.Rows[a].Cells[4].Value.ToString() + "€";
                table.Cell(1, 5).Range.Text = dataGridView1.Rows[a].Cells[5].Value.ToString() + "€";
                table.Cell(1, 6).Range.Text = dataGridView1.Rows[a].Cells[6].Value.ToString() + "€";
                table.Cell(1, 7).Range.Text = dataGridView1.Rows[a].Cells[7].Value.ToString() + "€";
                table.Cell(1, 8).Range.Text = dataGridView1.Rows[a].Cells[8].Value.ToString() + "€";
                table.Cell(1, 9).Range.Text = dataGridView1.Rows[a].Cells[9].Value.ToString() + "€";
                document.Tables[1].Rows.Add(document.Tables[1].Rows[1]);
            }
            table.Cell(1, 1).Range.Text = "Date";
            table.Cell(1, 2).Range.Text = "Motif";
            table.Cell(1, 3).Range.Text = "Trajet";
            table.Cell(1, 4).Range.Text = "Kms parcourus";
            table.Cell(1, 5).Range.Text = "Coût trajet";
            table.Cell(1, 6).Range.Text = "Péages";
            table.Cell(1, 7).Range.Text = "Repas";
            table.Cell(1, 8).Range.Text = "Hébergement";
            table.Cell(1, 9).Range.Text = "Total";
            UCHome           getTok   = new UCHome();
            string           getTotal = "select sum(totalCost) from slips where idMember = '" + getTok.returnToken() + "'";
            MySqlDataAdapter sumTotal = new MySqlDataAdapter(getTotal, coInsert);
            DataTable        sumDt    = new DataTable();

            sumTotal.Fill(sumDt);
            totalCostVar = sumDt.Rows[0][0].ToString();
            document.SaveAs2(ref save13, 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);
            document.Close();
            wordApp.Quit();
            CreateWordDocument(mainPathUser + @"\bordereauFillDataGridUser.docx", mainPathUser + @"\bordereauFileFillUser.docx");
            FormPDFUser Fc = new FormPDFUser();

            Fc.ShowDialog();
        }
コード例 #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            infapred.Clear();
            ZemelYch.Clear();
            Proiz.Clear();
            OsnPred.Clear();

            getPredpriati(TPredpriatia.Text);

            int idpred = getPredpriatia(TPredpriatia.Text);

            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter = "Document (*.docx) | *.docx";

            try
            {
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    var newpathdoc = sfd.FileName;

                    //TODO
                    var wordAPP = new Word.Application();
                    wordAPP.Visible = false;

                    var worddocument = wordAPP.Documents.Open(TemplateFileName);

                    ReplateWordDocument("{Predpriatia}", infapred[0], worddocument);
                    ReplateWordDocument("{DataTime}", infapred[1], worddocument);
                    ReplateWordDocument("{VidSobs}", infapred[2], worddocument);
                    ReplateWordDocument("{Adres}", infapred[3], worddocument);
                    ReplateWordDocument("{Users}", infapred[4], worddocument);
                    ReplateWordDocument("{Phone}", infapred[5], worddocument);

                    //Таблица 1
                    var n = 0;
                    getOsnPred(idpred.ToString());
                    Word.Table tab = worddocument.Tables[1];
                    for (int i = 2; i <= (OsnPred.Count / 3) + 1; i++)
                    {
                        tab.Rows.Add(Missing.Value);
                        tab.Cell(i, 1).Range.Text = OsnPred[n];
                        n++;
                        tab.Cell(i, 2).Range.Text = OsnPred[n];
                        n++;
                        tab.Cell(i, 3).Range.Text = OsnPred[n];
                        n++;
                    }

                    //Таблица 2
                    n = 0;
                    getZemelYch(idpred.ToString());
                    tab = worddocument.Tables[2];
                    for (int i = 2; i <= (ZemelYch.Count / 3) + 1; i++)
                    {
                        tab.Rows.Add(Missing.Value);
                        tab.Cell(i, 1).Range.Text = ZemelYch[n];
                        n++;
                        tab.Cell(i, 2).Range.Text = ZemelYch[n];
                        n++;
                        tab.Cell(i, 3).Range.Text = ZemelYch[n];
                        n++;
                    }

                    //Таблица 3
                    n = 0;
                    getProiz(idpred.ToString());
                    tab = worddocument.Tables[3];
                    for (int i = 2; i <= (Proiz.Count / 2) + 1; i++)
                    {
                        tab.Rows.Add(Missing.Value);
                        tab.Cell(i, 1).Range.Text = Proiz[n];
                        n++;
                        tab.Cell(i, 2).Range.Text = Proiz[n];
                        n++;
                    }

                    worddocument.SaveAs(newpathdoc);
                    wordAPP.Visible = true;

                    MessageBox.Show("Документ сохранен", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch
            {
                MessageBox.Show("Произошла ошибка.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
コード例 #27
0
        /// <summary>
        /// Создает и отправляет пользоваетеляю файл с результатами сесии группы
        /// </summary>
        /// <param name="subjectID">Идентификатор предмета</param>
        /// <param name="groupID">Идентификатор группы</param>
        /// <returns>Имя файла для загрузки</returns>
        public string Session(int subjectID, int groupID)
        {
            string fileName = "session" + "_" + DateTime.Now.ToString("dd_MM_yyyy") + ".docx";

            DeleteFile(fileName);
            Group @group = new Group(groupID);

            group.GetInformationAboutUserFromDB();
            Student[] students = group.GetStudent();
            Subject   subject  = new Subject(subjectID);

            subject.GetInformationAboutUserFromDB();
            Lecturer lecturer = new Lecturer(subject.LecturerID);

            lecturer.GetInformationAboutUserFromDB();
            Examination[] examinations = subject.GetSession(group.ID);
            if (examinations == null)
            {
                return(null);
            }
            Microsoft.Office.Interop.Word.Application applicationWord = new Microsoft.Office.Interop.Word.Application();

            applicationWord.Documents.Add(Type.Missing, false, Microsoft.Office.Interop.Word.WdNewDocumentType.wdNewBlankDocument, false);

            Microsoft.Office.Interop.Word.Document documentWord = applicationWord.Documents.get_Item(1);
            documentWord.Activate();

            //applicationWord.Visible = true;

            Microsoft.Office.Interop.Word.Paragraph documentParagraph = documentWord.Paragraphs.First;
            documentParagraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
            documentParagraph.Range.Font.Bold = 1;
            documentParagraph.Range.Text      = "Іспит";

            documentParagraph = documentWord.Paragraphs.Add().Next();
            documentParagraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            documentParagraph.Range.Font.Bold = 0;
            documentParagraph.Range.Text      = "Національний технічний університет України \"Київський політехнічний інститут\"";

            documentParagraph = documentWord.Paragraphs.Add().Next();
            documentParagraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            documentParagraph.Range.Font.Bold = 1;
            documentParagraph.Range.Text      = "Факультет інформатики та обчислювальної техніки";

            documentParagraph = documentWord.Paragraphs.Add().Next();
            documentParagraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            documentParagraph.Range.Font.Bold = 0;
            documentParagraph.Range.Text      = group.Name;

            documentParagraph = documentWord.Paragraphs.Add().Next();
            documentParagraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            documentParagraph.Range.Font.Bold = 1;
            documentParagraph.Range.Text      = "Заліково-екзаменаційна відомость № " + (new Random()).Next(20, 700);

            documentParagraph = documentWord.Paragraphs.Add().Next();
            documentParagraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            documentParagraph.Range.Font.Bold      = 0;
            documentParagraph.Range.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineSingle;
            documentParagraph.Range.Text           = subject.Name;

            documentParagraph = documentWord.Paragraphs.Add().Next();
            documentParagraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            documentParagraph.Range.Font.Bold      = 0;
            documentParagraph.Range.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;
            documentParagraph.Range.Text           = "за " + students[0].CurrentSemester + " навчальний семетр" + "\t\t Дата _____________";

            documentParagraph = documentWord.Paragraphs.Add().Next();
            documentParagraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            documentParagraph.Range.Font.Bold = 0;
            documentParagraph.Range.Text      = "Екзаменатор  " + lecturer.ShortName;

            documentParagraph = documentWord.Paragraphs.Add().Next();
            Microsoft.Office.Interop.Word.Table    table   = documentWord.Tables.Add(documentParagraph.Range, students.Length + 2, 7);
            Microsoft.Office.Interop.Word.Border[] borders = new Microsoft.Office.Interop.Word.Border[6];  //массив бордеров
            borders[0] = table.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft];           //левая граница
            borders[1] = table.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight];          //правая граница
            borders[2] = table.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop];            //нижняя граница
            borders[3] = table.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom];         //верхняя граница
            borders[4] = table.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal];     //горизонтальная граница
            borders[5] = table.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical];       //вертикальная граница
            foreach (Microsoft.Office.Interop.Word.Border border in borders)
            {
                border.LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;   //ставим стиль границы
                border.Color     = Microsoft.Office.Interop.Word.WdColor.wdColorBlack;            //задаем цвет границы
            }
            documentWord.Range(table.Cell(1, 1).Range.Start, table.Cell(2, 1).Range.End).Select();
            applicationWord.Selection.Cells.Merge();
            documentWord.Range(table.Cell(1, 2).Range.Start, table.Cell(2, 2).Range.End).Select();
            applicationWord.Selection.Cells.Merge();
            documentWord.Range(table.Cell(1, 3).Range.Start, table.Cell(2, 3).Range.End).Select();
            applicationWord.Selection.Cells.Merge();
            documentWord.Range(table.Cell(1, 5).Range.Start, table.Cell(1, 6).Range.End).Select();
            applicationWord.Selection.Cells.Merge();
            documentWord.Range(table.Cell(1, 6).Range.Start, table.Cell(2, 7).Range.End).Select();
            applicationWord.Selection.Cells.Merge();

            table.Cell(1, 1).Range.Text = "№\nз/п";
            table.Cell(1, 2).Range.Text = "Прізвище, ініціали студента";
            table.Cell(1, 3).Range.Text = "№ залікової книжки";
            table.Cell(1, 4).Range.Text = "Рейтингові бали";
            table.Cell(2, 4).Range.Text = "Всього";
            table.Cell(1, 5).Range.Text = "Результат";
            table.Cell(2, 5).Range.Text = "Оцінка ECTS";
            table.Cell(2, 6).Range.Text = "Традиційна оцінка";
            table.Cell(1, 6).Range.Text = "Підпис виклад.";

            for (int i = 0, end = students.Length; i < end; i++)
            {
                table.Cell(i + 3, 1).Range.Text = (i + 1).ToString();
                table.Cell(i + 3, 2).Range.Text = students[i].ShortName;
                table.Cell(i + 3, 3).Range.Text = students[i].RecordBook;
                table.Cell(i + 3, 4).Range.Text = examinations[i].Mark.ToString();
                table.Cell(i + 3, 5).Range.Text = Marks.ToBolognaSystem(examinations[i].Mark, 100);
                table.Cell(i + 3, 6).Range.Text = Marks.ToTraditional(Marks.ToBolognaSystem(examinations[i].Mark, 100));
            }

            documentWord.SaveAs(Server.MapPath("~/Files") + "\\" + fileName);
            documentWord.Close();
            applicationWord.Quit();
            return(fileName);
        }
コード例 #28
0
ファイル: WordHelper.cs プロジェクト: 985468944/Greenpeace
        /// <summary>
        /// 插入表格
        /// </summary>
        public void InsertTable()
        {
            object myNothing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Table table1 = _wordDocument.Tables.Add(_wordApplication.Selection.Range, 4, 3, ref myNothing, ref myNothing);
            _wordDocument.Tables[1].Cell(1, 1).Range.Text = "产品\n项目";
            _wordDocument.Tables[1].Cell(1, 2).Range.Text = "电脑";
            _wordDocument.Tables[1].Cell(1, 3).Range.Text = "手机";
            _wordDocument.Tables[1].Cell(2, 1).Range.Text = "重量(kg)";
            _wordDocument.Tables[1].Cell(3, 1).Range.Text = "价格(元)";
            _wordDocument.Tables[1].Cell(4, 1).Range.Text = "共同信息";
            _wordDocument.Tables[1].Cell(4, 2).Range.Text = "信息A";
            _wordDocument.Tables[1].Cell(4, 3).Range.Text = "信息B";
            table1.Select();
            table1.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter;//整个表格居中

            _wordApplication.Selection.Cells.VerticalAlignment   = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            _wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            _wordApplication.Selection.Cells.HeightRule          = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightExactly;
            _wordApplication.Selection.Cells.Height = 40;
            table1.Rows[2].Height = 20;
            table1.Rows[3].Height = 20;
            table1.Rows[4].Height = 20;
            table1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            _wordApplication.Selection.Cells.Width = 150;
            table1.Columns[1].Width = 75;
            table1.Cell(1, 1).Range.ParagraphFormat.Alignment      = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
            table1.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;


            _wordApplication.Selection.Cells.VerticalAlignment   = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            _wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            _wordApplication.Selection.Cells.HeightRule          = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightExactly;
            _wordApplication.Selection.Cells.Height = 40;
            table1.Rows[2].Height = 20; table1.Rows[3].Height = 20;
            table1.Rows[4].Height = 20;
            table1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            _wordApplication.Selection.Cells.Width = 150;
            table1.Columns[1].Width = 75;
            table1.Cell(1, 1).Range.ParagraphFormat.Alignment      = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
            table1.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

            //表头斜线
            table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Visible   = true;
            table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color     = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
            table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;


            //表格边框
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Color     = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Color     = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Visible = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Color   = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDoubleWavy;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Color     = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDoubleWavy;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Color     = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Color     = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;


            //合并单元格
            //_wordDocument.Tables[1].Cell(4, 2).Merge(table1.Cell(4, 3));
        }
コード例 #29
0
        private object G_str_path;                         //定义文件保存路径字段

        private void btn_New_Click(object sender, EventArgs e)
        {
            btn_New.Enabled = false;                                                  //停用新建按钮
            ThreadPool.QueueUserWorkItem(                                             //开始线程池
                (pp) =>                                                               //使用lambda表达式
            {
                G_wa               = new Microsoft.Office.Interop.Word.Application(); //创建应用程序对象
                object P_obj       = "Normal.dot";                                    //定义文档模板
                Word.Document P_wd = G_wa.Documents.Add(                              //向Word应用程序中添加文档
                    ref P_obj, ref G_missing, ref G_missing, ref G_missing);
                Word.Range P_Range = P_wd.Range(                                      //得到文档范围
                    ref G_missing, ref G_missing);
                DataTier P_DataTier = new DataTier();                                 //创建数据层对象
                List <InstanceClass> P_List_InstanceClass                             //得到数据集合
                          = P_DataTier.GetMessage();
                object o1 = Word.WdDefaultTableBehavior.                              //设置文档中表格格式
                            wdWord8TableBehavior;
                object o2 = Word.WdAutoFitBehavior.                                   //设置文档中表格格式
                            wdAutoFitWindow;
                Word.Table P_WordTable = P_Range.Tables.Add(P_Range,                  //在文档中添加表格
                                                            P_List_InstanceClass.Count + 2, 5, ref o1, ref o2);
                P_WordTable.Cell(1, 1).Range.Text = "ID";                             //向表格中添加信息
                P_WordTable.Cell(1, 2).Range.Text = "姓名";                             //向表格中添加信息
                P_WordTable.Cell(1, 3).Range.Text = "语文成绩";                           //向表格中添加信息
                P_WordTable.Cell(1, 4).Range.Text = "数学成绩";                           //向表格中添加信息
                P_WordTable.Cell(1, 5).Range.Text = "英语成绩";                           //向表格中添加信息
                for (int i = 2; i < P_List_InstanceClass.Count + 2; i++)
                {
                    P_WordTable.Cell(i, 1).Range.Text =    //向表格中添加信息
                                                        P_List_InstanceClass[i - 2].id.ToString();
                    P_WordTable.Cell(i, 2).Range.Text =    //向表格中添加信息
                                                        P_List_InstanceClass[i - 2].Name;
                    P_WordTable.Cell(i, 3).Range.Text =    //向表格中添加信息
                                                        P_List_InstanceClass[i - 2].Chinese.ToString();
                    P_WordTable.Cell(i, 4).Range.Text =    //向表格中添加信息
                                                        P_List_InstanceClass[i - 2].Math.ToString();
                    P_WordTable.Cell(i, 5).Range.Text =    //向表格中添加信息
                                                        P_List_InstanceClass[i - 2].English.ToString();
                }
                float P_Chinese = 0;                                 //定义变量用于计算数据列
                float P_Math    = 0;                                 //定义变量用于计算数据列
                float P_English = 0;                                 //定义变量用于计算数据列
                P_List_InstanceClass.
                ForEach((Instance) =>                                //使用Lambda表达式
                {
                    P_Chinese += ((InstanceClass)Instance).Chinese;  //计算数据列
                    P_Math    += ((InstanceClass)Instance).Math;     //计算数据列
                    P_English += ((InstanceClass)Instance).English;  //计算数据列
                });
                P_WordTable.Cell(P_List_InstanceClass.Count + 2,     //向表格中添加信息
                                 1).Range.Text = "科目总成绩";
                P_WordTable.Cell(P_List_InstanceClass.Count + 2, 3). //向表格中添加信息
                Range.Text = P_Chinese.ToString();
                P_WordTable.Cell(P_List_InstanceClass.Count + 2, 4). //向表格中添加信息
                Range.Text = P_Math.ToString();
                P_WordTable.Cell(P_List_InstanceClass.Count + 2, 5). //向表格中添加信息
                Range.Text = P_English.ToString();
                G_str_path = string.Format(                          //计算文件保存路径
                    @"{0}\{1}", G_FolderBrowserDialog.SelectedPath,
                    DateTime.Now.ToString("yyyy年M月d日h时s分m秒fff毫秒") + ".doc");
                P_wd.SaveAs(    //保存Word文件
                    ref G_str_path,
                    ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                    ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                    ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                    ref G_missing, ref G_missing, ref G_missing);
                ((Word._Application)G_wa.Application).Quit( //退出应用程序
                    ref G_missing, ref G_missing, ref G_missing);
                this.Invoke(                                //调用窗体线程
                    (MethodInvoker)(() =>                   //使用lambda表达式
                {
                    MessageBox.Show(                        //弹出消息对话框
                        "成功创建Word文档!", "提示!");
                    btn_display.Enabled = true;             //启用显示按钮
                }));
            });
        }
コード例 #30
0
        //оцінювання
        private void GradingBall(List <CheckedObj> list)
        {
            Word.Table table = application.Documents[1].Tables[12]; //об'єкт таблиці для заповнення

            if (firstTable == false)                                //якщо це перша таблиця
            {                                                       //додавання два рядка
                table.Rows.Add();
                table.Rows.Add();
            }
            firstTable = false; //змінюємо прапорець
            //відображення поточного семестру у шапку таблиці
            table.Cell(table.Rows.Count, 1).Range.Text = list[0].Course + " курс " + list[0].SemesterNum + " семестр" + " / " + list[0].Course + " course " + list[0].SemesterNum + " semester";
            //встановлення стилю тексту
            table.Cell(table.Rows.Count, 1).Range.Bold      = 1;
            table.Cell(table.Rows.Count, 1).Range.Font.Size = 14;
            table.Rows.Add();                    //додавання рядка

            int count = 1;                       // лічільник семестр

            for (int i = 0; i < list.Count; i++) //загальний цикл для виставлення оцінок
            {
                table.Rows.Add();                //додавання рядка
                //змінення стилю тексту
                table.Cell(table.Rows.Count, 1).Range.Bold      = 0;
                table.Cell(table.Rows.Count, 1).Range.Font.Size = 11;
                //якщо тип оцінки ЗНО
                if (list[i].Type == "ЗНО")
                {
                    table.Cell(table.Rows.Count, 1).Range.Text = count + "." + list[i].Name + "\n" + list[i].NameEN + "(ЗНО/IEE)";
                }
                else if (list[i].Type == "ДПА")//якщо тип оцінки ДПА
                {
                    table.Cell(table.Rows.Count, 1).Range.Text = count + "." + list[i].Name + "\n" + list[i].NameEN;
                }
                else //всі інщі типи
                {
                    table.Cell(table.Rows.Count, 1).Range.Text = count + "." + list[i].Name + "\n" + list[i].NameEN + " - " + list[i].OverSize + " г. / h.";
                }

                //якщо система числення <= 5
                if (list[i].Value <= 5)
                {
                    //створення запиту
                    command = new SQLiteCommand("SELECT ValueText, ValueTextEN FROM ValueFive WHERE Value = @value", Program.conn);
                }
                else //в інших випадках
                {
                    //створення запиту
                    command = new SQLiteCommand("SELECT ValueText, ValueTextEN FROM ValueTwelve WHERE Value = @value", Program.conn);
                }
                //додавання параметрів
                command.Parameters.Add(new SQLiteParameter("@value", list[i].Value.ToString()));
                dataReader = command.ExecuteReader(); //виконання команди
                while (dataReader.Read())
                {
                    if (list[i].Type == "ДПА") //якщо тип оцінки ДПА
                    {
                        table.Rows[table.Rows.Count].Cells[2].Range.Text = list[i].Value.ToString() + "(" + dataReader[0].ToString() + "/" + dataReader[1].ToString() + ") - Державний іспит/State Exam";
                    }
                    else if (list[i].Type == "ЗНО") //якщо ЗНО
                    {
                        table.Rows[table.Rows.Count].Cells[2].Range.Text = list[i].Value.ToString() + "(" + dataReader[0].ToString() + "/" + dataReader[1].ToString() + ") - Іспит/Exam";
                    }
                    else //в інших випадках
                    {
                        table.Rows[table.Rows.Count].Cells[2].Range.Text = list[i].Value.ToString() + "(" + dataReader[0].ToString() + "/" + dataReader[1].ToString() + ") - " + list[i].Type + "/Exam";
                    }
                }
                count++; //наступний семестр
            }
        }
コード例 #31
0
        //создание отчета для ЦА
        private async Task CreateReportCA(string file_path)
        {
            await Task.Run(() =>
            {
                //задаем текст и значения statusStrip
                this.Invoke((Action)delegate
                {
                    tsProgressBar.Value = 0;
                    tsStatusLabel.Text = "Открытие шаблона";
                });
                //берем значения рабочих и дней месяца
                string work_days = settings.tbWorkDays.Text;
                string month_in_days = settings.tbMonthDays.Text;
                //объявляем переменные для подсчета кол-ва работ проводимых каждый день и только в рабочие дни
                int count_work_days = 0;
                int count_month_in_days = 0;
                //создаем документ Word на основе шаблона и делаем его невидимым
                word_app = new Word.Application();
                word_doc = word_app.Documents.Add(file_path);
                word_app.Visible = false;
                //заменяем в документе <Period_month> на период
                WordReplace("<Period_month>", StringPeriod(true));
                //заменяем все <WorkDays> на число рабочих дней, а также подсчитываем их кол-во
                WordReplace("<WorkDays>", work_days, ref count_work_days);
                //также заменяем <MonthInDays> на число дней в месяце, а также посчитываем их кол-во
                WordReplace("<MonthInDays>", month_in_days, ref count_month_in_days);
                //заменяем переменную в документе на текущий период
                dynamic word_vars = word_doc.CustomDocumentProperties;
                dynamic word_var_period = word_vars["_Период"].Value = StringPeriod(true);
                //объявляем массив для дней из таблицы
                var dates_from_table = new List<DateTime>();
                //проход по таблице 
                for (int i = 0; i < dgvTable.Rows.Count; i++)
                {
                    //добавляем в массив каждую дату из таблицы
                    dates_from_table.Add((DateTime)dgvTable.Rows[i].Cells[0].Value);
                }
                //делаем словарь (Dictonary) с ключом - Дата, и значением - число заявок в этот день
                var dates_with_count_tickets = dates_from_table
                    .Select(DateTime => new { Date = DateTime, Count = dates_from_table.Count(d => d == DateTime) })
                    .Where(obj => obj.Count >= 1)
                    .Distinct()
                    .ToDictionary(obj => obj.Date, obj => obj.Count);
                //объявляем зубчатый массив [][,], где [день][кол-во заявок(кол-во строк),строки "дата завершения","номер кабинета","содержание","метод обращения"(кол-во столбцов)]
                object[][,] tickets = new object[dates_with_count_tickets.Count][,];
                //удаляем дубликаты из массива с днями
                dates_from_table = dates_from_table.Distinct().ToList();
                //объявляем перменные для номера дня из зубчатого массива и для индекса строки таблицы
                int day = 0;
                int row = 0;
                //проход по словарю
                foreach (var d in dates_with_count_tickets)
                {
                    //объявляем массив для дня с числом строк
                    tickets[day] = new object[d.Value, 4];
                    //проход по строкам
                    for (int i = 0; i < d.Value; i++)
                    {
                        //по столбцам
                        for (int j = 0; j < 4; j++)
                        {
                            //заносим в массив данные из таблицы
                            tickets[day][i, j] = dgvTable.Rows[row].Cells[j].Value.ToString();
                        }
                        //переход на след строку
                        row++;
                    }
                    //след день
                    day++;
                }
                //объвляем переменную для второй таблицы
                word_table2 = word_doc.Tables[2];
                // ищем последную ячейку
                Word.Cell last_cell = word_table2.Range.Cells[word_table2.Range.Cells.Count];
                // первая ячейка в последней строке
                Word.Cell cell_position_to_insert_rows = word_table2.Cell(last_cell.RowIndex, 1);
                // индекс строки, в которую будут записываться данные
                int row_to_insert_tickets = cell_position_to_insert_rows.RowIndex;
                // строка которая должна быть раскрашена
                int row_to_color = row_to_insert_tickets + 1;
                // индекс массива с определенным днем
                int number_of_massive = 0;
                // индекс ячейки, с которой необходимо начать объединять ячейки в первом столбце
                int row_start_merge = row_to_insert_tickets;
                // объявление переменной для подсчета кол-во плановых работ
                int tickets_planovie = 0;
                // переменная для подсчета обращений
                int tickets_obrascheniya = 0;
                // вставка необходимого кол-ва строк, -1 - т.к. 1 пустая строка уже вставлена
                for (int i = 0; i < dgvTable.Rows.Count - 1; i++)
                {
                    cell_position_to_insert_rows.Range.Rows.Add();
                    this.Invoke((Action)delegate
                    {
                        tsStatusLabel.Text = "Вставка строк";
                        tsProgressBar.Maximum = dgvTable.Rows.Count-1;
                        tsProgressBar.Value++;
                    });
                }
                this.Invoke((Action)delegate
                {
                    tsStatusLabel.Text = "Заполнение документа";
                    tsProgressBar.Value = 0;
                });
                // проход по массиву
                for (int i = 0; i < tickets.Length; i++)
                {
                    // первая ячейка в строке - дата
                    DateTime first_cell_in_row = (DateTime)Convert.ChangeType(tickets[number_of_massive][0, 0], typeof(DateTime));
                    // вставляем дату в документ
                    word_table2.Cell(row_to_insert_tickets, 1).Range.Text = first_cell_in_row.ToString("dd.MM.yyyy");
                    // проход по заявкам в каждом дне
                    for (int j = 0; j < tickets[number_of_massive].GetLength(0); j++)
                    {
                        //вставляем в таблицу данные из массива
                        word_table2.Cell(row_to_insert_tickets, 2).Range.Text = tickets[number_of_massive][j, 1].ToString();
                        word_table2.Cell(row_to_insert_tickets, 3).Range.Text = tickets[number_of_massive][j, 2].ToString();
                        word_table2.Cell(row_to_insert_tickets, 4).Range.Text = tickets[number_of_massive][j, 3].ToString();
                        // подсчитываем плановые
                        if (word_table2.Cell(row_to_insert_tickets, 4).Range.Text.Contains("Плановые работы"))
                        {
                            tickets_planovie++;
                        }
                        // если не плановые, то увеличиваем обращения
                        else tickets_obrascheniya++;
                        // переходим на след строку в документе
                        row_to_insert_tickets++;
                    }
                    // если строки не равны, то объеденияем ячейки
                    if (!(row_start_merge == row_to_insert_tickets - 1))
                    {
                        word_table2.Cell(row_start_merge, 1).Merge(word_table2.Cell(row_to_insert_tickets - 1, 1));
                    }
                    // переходим к след дню
                    row_start_merge = row_to_insert_tickets;
                    number_of_massive++;
                    this.Invoke((Action)delegate
                    {
                        tsStatusLabel.Text = "Заполнение документа";
                        tsProgressBar.Maximum = tickets.Length;
                        tsProgressBar.Value++;
                    });
                }
                // объявляем переменную для первой таблицы, в которую пишутся итоги
                word_table1 = word_doc.Tables[1];
                // берем все месячные работы из начала документа
                int planovie_calendar = ((int.Parse(work_days) * count_work_days) + (int.Parse(month_in_days) * count_month_in_days));
                // пишем кол-во обращений
                word_table1.Rows[2].Cells[2].Range.Text = tickets_obrascheniya.ToString();
                // пишем кол-во плановых работ
                word_table1.Rows[3].Cells[2].Range.Text = (planovie_calendar + tickets_planovie).ToString();
                // пишем общее кол-во заявок
                word_table1.Rows[4].Cells[2].Range.Text = (planovie_calendar + tickets_planovie + tickets_obrascheniya).ToString();
                // цвет для закраски чередующихся строк
                Color color_background = Color.FromArgb(222, 234, 246);
                // приводим цвет к совместимому с Word
                var word_background_color = (Microsoft.Office.Interop.Word.WdColor)(color_background.R + 0x100 * color_background.G + 0x10000 * color_background.B); ;
                // закрашиваем каждую вторую строку
                while (row_to_color < row_to_insert_tickets)
                {
                    word_table2.Cell(row_to_color, 2).Shading.BackgroundPatternColor = word_background_color;
                    word_table2.Cell(row_to_color, 3).Shading.BackgroundPatternColor = word_background_color;
                    word_table2.Cell(row_to_color, 4).Shading.BackgroundPatternColor = word_background_color;
                    row_to_color += 2;
                }

                this.Invoke((Action)delegate
                {
                    tsProgressBar.Value = 0;
                    tsStatusLabel.Text = "Готово!";
                    // окно сохранения документа
                    SaveFileDialog sfd = new SaveFileDialog();
                    // расширение по умеолчанию
                    sfd.DefaultExt = "docx";
                    // автоматом добавлять расширение
                    sfd.AddExtension = true;
                    // фильтр выводимых файлов в окне
                    sfd.Filter = "Документ Word(*.docx)|*.docx";
                    // фильтр по умолчанию
                    sfd.FilterIndex = 1;
                    // задаем имя документу
                    sfd.FileName = "Еженедельный-Месячный отчет " + StringPeriod(false);
                    // при нажатии "ОК"
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        // сохраняем документ
                        word_doc.SaveAs2(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                        // выводим окно с сообщением
                        MessageBox.Show("Готово!\nСхоранено в "+sfd.FileName);
                        // закрываем документ с сохранием
                        word_doc.Close(Word.WdSaveOptions.wdSaveChanges, Type.Missing, Type.Missing);
                        // закрываем приложение Word
                        word_app.Quit(Type.Missing, Type.Missing, Type.Missing);
                        // прибиваем процесс Word'a
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(word_app);
                        // сбрасываем ссылки на Word
                        word_doc = null;
                        word_app = null;
                        // пробуем удалить из памяти лишнее
                        GC.Collect();
                    }
                    // при любом другом действии
                    else
                    {
                        // закрываем документ без сохранения
                        word_doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Type.Missing, Type.Missing);
                        // закрываем приложение без сохранения
                        word_app.Quit(Word.WdSaveOptions.wdDoNotSaveChanges, Type.Missing, Type.Missing);
                        // убаваем процесс
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(word_app);
                        // сбрасываем ссылки
                        word_doc = null;
                        word_app = null;
                        // запуск сборщика мусора
                        GC.Collect();
                    }
                });


            });
        }
コード例 #32
0
 /// <summary>
 /// 返回指定单元格中的数据
 /// </summary>
 /// <param name="表的序号"></param>
 /// <param name="行号"></param>
 /// <param name="第几列"></param>
 /// <returns></returns>
 public string ReadWord(int tableIndex, int rowIndex, int colIndex)
 {
     //Give the value to the tow Int32 params.
     try
     {
         if (openState == true)
         {
             table = doc.Tables[tableIndex];
             string text = table.Cell(rowIndex, colIndex).Range.Text.ToString();
             text = text.Substring(0, text.Length - 2);    //去除尾部的mark
             return text;
         }
         else
         {
             return "";
         }
     }
     catch (Exception ee)
     {
         return ee.ToString();
     }
 }
コード例 #33
0
 /// <summary>
 /// 向指定单元格中写值
 /// </summary>
 /// <param name="表的序号"></param>
 /// <param name="行号"></param>
 /// <param name="第几列"></param>
 /// <param name="要写入的值"></param>
 /// <returns></returns>
 public bool WriteToWord(int tableIndex, int rowIndex, int colIndex, string text)
 {
     //Give the value to the tow Int32 params.
     try
     {
         if (openState == true)
         {
             table = doc.Tables[tableIndex];
             table.Cell(rowIndex, colIndex).Range.Text = text;
             return true;
         }
         else
         {
             return false;
         }
     }
     catch (Exception ee)
     {
         return false;
     }
 }
コード例 #34
0
 public DataTable WordTable(int tableIndex)
 {
     DataTable dt = new DataTable();
     if (openState == true)
     {
         table = doc.Tables[tableIndex];
         for (int ii = 0; ii < table.Columns.Count; ii++)
         {
             dt.Columns.Add("cl" + ii.ToString(), typeof(string));
         }
         for (int ii = 0; ii < table.Rows.Count; ii++)
         {
             DataRow rw = dt.NewRow();
             for (int jj = 0; jj < table.Columns.Count; jj++)
             {
                 string text = table.Cell(ii + 1, jj + 1).Range.Text.ToString();
                 //string text = table.Rows[ii].Cells[jj].ToString();
                 text = text.Substring(0, text.Length - 2);
                 rw["cl" + (jj).ToString()] = text;
             }
             dt.Rows.Add(rw);
         }
     }
     return dt;
 }