예제 #1
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;
 }
예제 #2
0
        public void addTable(object bookmark, System.Data.DataTable dt)
        {
            try
            {
                int    cols    = dt.Columns.Count;
                int    rows    = dt.Rows.Count;
                object nothing = Missing.Value;

                Word.Range wrdRng = wDoc.Bookmarks.get_Item(ref bookmark).Range;
                Word.Table table  = wDoc.Tables.Add(wrdRng, rows + 1, cols, ref nothing, ref nothing);
                table.Borders.InsideLineStyle  = Word.WdLineStyle.wdLineStyleSingle;
                table.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
                table.PreferredWidthType       = Word.WdPreferredWidthType.wdPreferredWidthPercent;
                table.Columns[1].Width         = 100;
                table.Columns[2].Width         = 400;

                // table header
                for (int i = 0; i < cols; i++)
                {
                    table.Cell(1, i + 1).Range.Text = dt.Columns[i].ColumnName;
                    table.Cell(1, i + 1).Range.Shading.ForegroundPatternColor
                        = Word.WdColor.wdColorGray25;
                    table.Cell(1, i + 1).Height = 35;
                }

                object            idx      = 1;
                Word.ListTemplate listTemp = wApp.ListGalleries[Word.WdListGalleryType.wdNumberGallery]
                                             .ListTemplates.get_Item(ref idx);
                object bContinuousPrev      = false;
                object applyTo              = Missing.Value;
                object defaultListBehaviour = Missing.Value;

                for (int i = 0; i < rows; i++)
                {
                    for (int j = 0; j < cols; j++)
                    {
                        Word.Cell cell = table.Cell(i + 2, j + 1);

                        object   obj   = dt.Rows[i][j];
                        string   txt   = obj == null ? "" : obj.ToString();
                        string[] lines = txt.Split(new string[] { "^n" },
                                                   StringSplitOptions.RemoveEmptyEntries);


                        cell.Range.Text = lines[0].Trim();

                        if (lines.Length > 1)
                        {
                            cell.Range.Paragraphs[1].Range.ListFormat.ApplyNumberDefault();
                            for (int k = 1; k < lines.Length; k++)
                            {
                                Word.Paragraph p = cell.Range.Paragraphs.Add();
                                p.Range.Text = lines[k].Trim();
                                p.Range.ListFormat.ApplyNumberDefault();
                                object o = p.Range.ParagraphStyle;
                            }

                            for (int k = 0; k < cell.Range.Paragraphs.Count; k++)
                            {
                                Word.Paragraph p = cell.Range.Paragraphs[k + 1];
                                p.Range.ListFormat.ApplyListTemplate(listTemp, bContinuousPrev,
                                                                     applyTo, defaultListBehaviour);
                                p.Range.Select();
                                wApp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly;
                                wApp.Selection.ParagraphFormat.LineSpacing     = 14f;
                                wApp.Selection.ParagraphFormat.LineUnitAfter   = 0.5f;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }
예제 #3
0
        public static void Export(ExportData data)
        {
            // копируем файл
            System.IO.File.Copy(data.nameFileTemplate, data.nameFileExport, true);

            // открываем ворд и документ вордовский (только что скопированный шаблон)
            Word.Application wordApp = new Word.Application();

            Word.Document document = wordApp.Documents.OpenNoRepairDialog(data.nameFileExport);
            document.Activate();

            // выбираем таблицу в ворде
            Word.Table table = document.Tables[data.tableIndex];

            // Добавление строки в таблицу
            // добавляет почему-то строку перед существующей
            // поэтому проще сначала создать нужное количество строк
            // а потом пройтись по ним и заполнить каждую
            int numRows = data.valuesCustomValues.Count - 1;

            for (int i = 0; i < numRows; i++)
            {
                // дублирование пустой строки таблицы
                var row = table.Rows.Add(table.Rows[1]);
            }


            // пройтись по каждой строке таблицы и через Cells[index] заполнить ее
            int numRow = 1;             // порядковый номер

            foreach (Word.Row row in table.Rows)
            {
                // порядковый номер строки
                row.Cells[1].Range.Text = (numRow++).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[numRow - 2][k];
                }
            }

            // замена текста
            void ReplaceText(string TextToReplace, string TextReplaceWith)
            {
                document.Content.Find.Execute(TextToReplace, false, true, false, false, false, true, 1, false, TextReplaceWith, 2, false, false, false, false);
            }

            int numItems = data.textToReplace.Count;

            for (int i = 0; i < numItems; i++)
            {
                ReplaceText(data.textToReplace[i], data.textReplaceWith[i]);
            }

            // конец экспорта
            if (data.openFileExport)
            {
                // сохранить изменения и открыть документ
                document.Save();
                wordApp.Visible = true;
            }
            else
            {
                // для закрытия документа без показа
                document.Save();
                document.Close();
                wordApp.Quit();
            }
        }
예제 #4
0
        /// <summary>
        /// 添加土工常规试验统计表格
        /// </summary>
        /// <param name="_rstStatistic">土工常规试验统计数据</param>
        /// <returns></returns>
        public MSWord.Table AddRSTStatisticTable(List <StatisticRST> _rstStatistic)
        {
            // 去除统计数为0的分层的统计数据
            for (int i = _rstStatistic.Count / 14 - 1; i > -1; i--)
            {
                bool isZero = true;

                for (int j = 13; j > -1; j--)
                {
                    if (_rstStatistic[j + i * 14].Count != 0)
                    {
                        isZero = false;
                    }
                }

                if (isZero)
                {
                    for (int j = 13; j > -1; j--)
                    {
                        _rstStatistic.RemoveAt(j + i * 14);
                    }
                }
            }

            // 填写表格标题
            Doc.Paragraphs.Last.Range.Text                = "表4 土工常规试验成果统计表";
            Doc.Paragraphs.Last.Range.Font.Bold           = 1;
            Doc.Paragraphs.Last.Range.Font.Size           = 12;
            App.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            object unite = MSWord.WdUnits.wdStory;

            App.Selection.EndKey(ref unite, ref Nothing);

            // 定义表格对象
            MSWord.Table table = Tables.Add(App.Selection.Range, _rstStatistic.Count / 14 * 8 + 1, 16, ref Nothing, ref Nothing);

            // 填充列标题
            string[] rowheader = new string[]
            {
                "层号及名称",
                "统\n计\n名\n称",
                "含\n水\n量",
                "天\n然\n密\n度",
                "比\n重",
                "孔\n隙\n比",
                "饱\n和\n度",
                "液\n限",
                "塑\n限",
                "塑\n性\n指\n数",
                "液\n性\n指\n数",
                "压\n缩\n系\n数",
                "压\n缩\n模\n量",
                "内\n摩\n擦\n角",
                "粘\n聚\n力",
                "渗\n透\n系\n数"
            };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Cell(1, i).Range.Text = rowheader[i - 1];
            }

            // 设置文档格式
            Doc.PageSetup.LeftMargin  = 50F;
            Doc.PageSetup.RightMargin = 50F;

            // 设置表格格式
            table.Select();
            App.Selection.Tables[1].Rows.Alignment = WdRowAlignment.wdAlignRowCenter;

            foreach (Row row in table.Rows)
            {
                row.Range.Bold = 0;
            }
            table.Rows[1].Range.Bold = 1;
            for (int i = 0; i < _rstStatistic.Count / 14; i++)
            {
                table.Rows[5 + i * 8].Range.Bold = 1;
                table.Rows[9 + i * 8].Range.Bold = 1;
            }

            table.Rows[1].Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceExactly;
            for (int i = 1; i <= table.Rows.Count; i++)
            {
                table.Cell(i, 1).Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceExactly;
            }

            table.Range.Font.Size = 9.0F;

            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

            table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle  = MSWord.WdLineStyle.wdLineStyleSingle;

            float[] columnWidth = new float[] { 20, 50, 30, 30, 30, 30, 35, 30, 30, 30, 30, 30, 30, 30, 30, 40 };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Columns[i].Width = columnWidth[i - 1];
            }

            // 填充试验数据
            for (int i = 0; i < _rstStatistic.Count / 14; i++)
            {
                int startRow = 2 + i * 8;

                table.Cell(startRow, 1).Range.Text = _rstStatistic[i * 14].Layer + " " + _rstStatistic[i * 14].Name;

                string[] type = new string[] { "统计数", "最大值", "最小值", "平均值", "标准差", "变异系数", "修正系数", "标准值" };
                for (int j = 0; j < 8; j++)
                {
                    table.Cell(startRow + j, 2).Range.Text = type[j];
                }

                for (int j = 0; j < 14; j++)
                {
                    if (j == 0 || j == 4 || j == 5 || j == 6 || j == 7 || j == 10 || j == 11 || j == 12)
                    {
                        table.Cell(startRow, 3 + j).Range.Text     = _rstStatistic[j + i * 14].Count.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Count.ToString("0");
                        table.Cell(startRow + 1, 3 + j).Range.Text = _rstStatistic[j + i * 14].Max.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Max.ToString("0.0");
                        table.Cell(startRow + 2, 3 + j).Range.Text = _rstStatistic[j + i * 14].Min.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Min.ToString("0.0");
                        table.Cell(startRow + 3, 3 + j).Range.Text = _rstStatistic[j + i * 14].Average.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Average.ToString("0.0");
                        table.Cell(startRow + 4, 3 + j).Range.Text = _rstStatistic[j + i * 14].StandardDeviation.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].StandardDeviation.ToString("0.0");
                        table.Cell(startRow + 5, 3 + j).Range.Text = _rstStatistic[j + i * 14].VariableCoefficient.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].VariableCoefficient.ToString("0.00");
                        table.Cell(startRow + 6, 3 + j).Range.Text = _rstStatistic[j + i * 14].CorrectionCoefficient.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].CorrectionCoefficient.ToString("0.00");
                        table.Cell(startRow + 7, 3 + j).Range.Text = _rstStatistic[j + i * 14].StandardValue.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].StandardValue.ToString("0.0");
                    }
                    else if (j == 1 || j == 2 || j == 3 || j == 8 || j == 9)
                    {
                        table.Cell(startRow, 3 + j).Range.Text     = _rstStatistic[j + i * 14].Count.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Count.ToString("0");
                        table.Cell(startRow + 1, 3 + j).Range.Text = _rstStatistic[j + i * 14].Max.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Max.ToString("0.00");
                        table.Cell(startRow + 2, 3 + j).Range.Text = _rstStatistic[j + i * 14].Min.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Min.ToString("0.00");
                        table.Cell(startRow + 3, 3 + j).Range.Text = _rstStatistic[j + i * 14].Average.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Average.ToString("0.00");
                        table.Cell(startRow + 4, 3 + j).Range.Text = _rstStatistic[j + i * 14].StandardDeviation.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].StandardDeviation.ToString("0.00");
                        table.Cell(startRow + 5, 3 + j).Range.Text = _rstStatistic[j + i * 14].VariableCoefficient.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].VariableCoefficient.ToString("0.00");
                        table.Cell(startRow + 6, 3 + j).Range.Text = _rstStatistic[j + i * 14].CorrectionCoefficient.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].CorrectionCoefficient.ToString("0.00");
                        table.Cell(startRow + 7, 3 + j).Range.Text = _rstStatistic[j + i * 14].StandardValue.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].StandardValue.ToString("0.00");
                    }
                    else
                    {
                        table.Cell(startRow, 3 + j).Range.Text     = _rstStatistic[j + i * 14].Count.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Count.ToString("0");
                        table.Cell(startRow + 1, 3 + j).Range.Text = _rstStatistic[j + i * 14].Max.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Max.ToString("0.0E0");
                        table.Cell(startRow + 2, 3 + j).Range.Text = _rstStatistic[j + i * 14].Min.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Min.ToString("0.0E0");
                        table.Cell(startRow + 3, 3 + j).Range.Text = _rstStatistic[j + i * 14].Average.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Average.ToString("0.0E0");
                        table.Cell(startRow + 4, 3 + j).Range.Text = _rstStatistic[j + i * 14].StandardDeviation.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].StandardDeviation.ToString("0.0E0");
                        table.Cell(startRow + 5, 3 + j).Range.Text = _rstStatistic[j + i * 14].VariableCoefficient.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].VariableCoefficient.ToString("0.00");
                        table.Cell(startRow + 6, 3 + j).Range.Text = _rstStatistic[j + i * 14].CorrectionCoefficient.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].CorrectionCoefficient.ToString("0.00");
                        table.Cell(startRow + 7, 3 + j).Range.Text = _rstStatistic[j + i * 14].StandardValue.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].StandardValue.ToString("0.0E0");
                    }
                }
            }

            // 合并层号及名称单元格
            for (int i = 0; i < _rstStatistic.Count / 14; i++)
            {
                table.Cell(2 + i * 8, 1).Merge(table.Cell(9 + i * 8, 1));
            }

            // 返回
            return(table);
        }
예제 #5
0
        /// <summary>
        /// 添加抗剪强度综合取值表
        /// </summary>
        /// <param name="_ssStatistic">抗剪强度综合取值数据</param>
        /// <returns></returns>
        public MSWord.Table AddShearingStrengthTable(List <ShearingStrengthCalculation.ShearingStrength> _ssStatistic)
        {
            // 填写表格标题
            Doc.Paragraphs.Last.Range.Text                = "表7 抗剪强度综合取值表";
            Doc.Paragraphs.Last.Range.Font.Bold           = 1;
            Doc.Paragraphs.Last.Range.Font.Size           = 12;
            App.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            object unite = MSWord.WdUnits.wdStory;

            App.Selection.EndKey(ref unite, ref Nothing);

            // 定义表格对象
            MSWord.Table table = Tables.Add(App.Selection.Range, _ssStatistic.Count + 2, 11, ref Nothing, ref Nothing);

            // 填充列标题
            table.Cell(1, 1).Range.Text  = "分层编号及名称";
            table.Cell(1, 2).Range.Text  = "土工试验";
            table.Cell(1, 4).Range.Text  = "静力触探试验";
            table.Cell(1, 7).Range.Text  = "标贯/动探";
            table.Cell(1, 10).Range.Text = "综合取值";
            string[] rowheader = new string[]
            {
                "φ\n(kPa)",
                "C\n(MPa)",
                "Ps\n(MPa)",
                "φ\n(kPa)",
                "C\n(MPa)",
                "N\n(击)",
                "φ\n(kPa)",
                "C\n(MPa)",
                "φ\n(kPa)",
                "C\n(MPa)"
            };
            for (int i = 1; i < table.Columns.Count; i++)
            {
                table.Cell(2, i + 1).Range.Text = rowheader[i - 1];
            }

            // 设置文档格式
            Doc.PageSetup.LeftMargin  = 50F;
            Doc.PageSetup.RightMargin = 50F;

            // 设置表格格式
            table.Select();
            App.Selection.Tables[1].Rows.Alignment = WdRowAlignment.wdAlignRowCenter;

            foreach (Row row in table.Rows)
            {
                row.Range.Bold           = 0;
                row.Cells[10].Range.Bold = 1;
                row.Cells[11].Range.Bold = 1;
            }
            table.Rows[1].Range.Bold = 1;

            table.Range.Font.Size = 10.0F;

            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

            table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle  = MSWord.WdLineStyle.wdLineStyleSingle;

            float[] columnWidth = new float[] { 100, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40 };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Columns[i].Width = columnWidth[i - 1];
            }

            // 填充试验数据
            for (int i = 0; i < _ssStatistic.Count; i++)
            {
                table.Cell(i + 3, 1).Range.Text  = _ssStatistic[i].layerInfo;
                table.Cell(i + 3, 2).Range.Text  = _ssStatistic[i].FrictionByRst == "-0.19880205" || _ssStatistic[i].FrictionByRst == "-0.2" ? "/" : _ssStatistic[i].FrictionByRst;
                table.Cell(i + 3, 3).Range.Text  = _ssStatistic[i].CohesionByRst == "-0.19880205" || _ssStatistic[i].CohesionByRst == "-0.2" ? "/" : _ssStatistic[i].CohesionByRst;
                table.Cell(i + 3, 4).Range.Text  = _ssStatistic[i].CptParameter == "-0.19880205" || _ssStatistic[i].CptParameter == "-0.2" ? "/" : _ssStatistic[i].CptParameter;
                table.Cell(i + 3, 5).Range.Text  = _ssStatistic[i].FrictionByCpt == "-0.19880205" || _ssStatistic[i].FrictionByCpt == "-0.2" ? "/" : _ssStatistic[i].FrictionByCpt;
                table.Cell(i + 3, 6).Range.Text  = _ssStatistic[i].CohesionByRst == "-0.19880205" || _ssStatistic[i].CohesionByRst == "-0.2" ? "/" : _ssStatistic[i].CohesionByRst;
                table.Cell(i + 3, 7).Range.Text  = _ssStatistic[i].NTestParameter == "-0.19880205" || _ssStatistic[i].NTestParameter == "-0.2" ? "/" : _ssStatistic[i].NTestParameter;
                table.Cell(i + 3, 8).Range.Text  = _ssStatistic[i].FrictionByNTest == "-0.19880205" || _ssStatistic[i].FrictionByNTest == "-0.2" ? "/" : _ssStatistic[i].FrictionByNTest;
                table.Cell(i + 3, 9).Range.Text  = _ssStatistic[i].CohesionByNTest == "-0.19880205" || _ssStatistic[i].CohesionByNTest == "-0.2" ? "/" : _ssStatistic[i].CohesionByNTest;
                table.Cell(i + 3, 10).Range.Text = _ssStatistic[i].FrictionFinal == "-0.19880205" || _ssStatistic[i].FrictionFinal == "-0.2" ? "/" : _ssStatistic[i].FrictionFinal;
                table.Cell(i + 3, 11).Range.Text = _ssStatistic[i].CohesionFinal == "-0.19880205" || _ssStatistic[i].CohesionFinal == "-0.2" ? "/" : _ssStatistic[i].CohesionFinal;
            }

            // 合并层号及名称单元格
            table.Cell(1, 10).Merge(table.Cell(1, 11));
            table.Cell(1, 7).Merge(table.Cell(1, 9));
            table.Cell(1, 4).Merge(table.Cell(1, 6));
            table.Cell(1, 2).Merge(table.Cell(1, 3));
            table.Cell(1, 1).Merge(table.Cell(2, 1));

            // 返回
            return(table);
        }
        private void CreateDocument()
        {
            try
            {
                //Create an instance for word app
                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

                //Set animation status for word application
                winword.ShowAnimation = false;

                //Set status for word application is to be visible or not.
                winword.Visible = false;

                //Create a missing variable for missing value
                object missing = System.Reflection.Missing.Value;

                //Create a new document
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                //Add header into the document
                foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
                {
                    //Get the header range and add the header details.
                    Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                    headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    headerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
                    headerRange.Font.Size = 10;
                    headerRange.Text      = "Header text goes here";
                }

                //Add the footers into the document
                foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                {
                    //Get the footer range and add the footer details.
                    Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    footerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
                    footerRange.Font.Size                 = 10;
                    footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    footerRange.Text = "Footer text goes here";
                }

                //adding text to document
                document.Content.SetRange(0, 0);
                document.Content.Text = "This is test document " + Environment.NewLine;

                //Add paragraph with Heading 1 style
                Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
                object styleHeading1 = "Heading 1";
                para1.Range.set_Style(ref styleHeading1);
                para1.Range.Text = "Para 1 text";
                para1.Range.InsertParagraphAfter();

                //Add paragraph with Heading 2 style
                Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
                object styleHeading2 = "Heading 2";
                para2.Range.set_Style(ref styleHeading2);
                para2.Range.Text = "Para 2 text";
                para2.Range.InsertParagraphAfter();

                //Create a 5X5 table and insert some dummy record
                Table firstTable = document.Tables.Add(para1.Range, 5, 5, ref missing, ref missing);

                firstTable.Borders.Enable = 1;
                foreach (Row row in firstTable.Rows)
                {
                    foreach (Cell cell in row.Cells)
                    {
                        //Header row
                        if (cell.RowIndex == 1)
                        {
                            cell.Range.Text      = "Column " + cell.ColumnIndex.ToString();
                            cell.Range.Font.Bold = 1;
                            //other format properties goes here
                            cell.Range.Font.Name = "verdana";
                            cell.Range.Font.Size = 10;
                            //cell.Range.Font.ColorIndex = WdColorIndex.wdGray25;
                            cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                            //Center alignment for the Header cells
                            cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                        }
                        //Data row
                        else
                        {
                            cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString();
                        }
                    }
                }

                //Save the document
                object filename = $"{Directory.GetCurrentDirectory()}/latesttemp1.docx";
                document.SaveAs2(ref filename);
                document.Close(ref missing, ref missing, ref missing);
                document = null;
                winword.Quit(ref missing, ref missing, ref missing);
                winword = null;
                MessageBox.Show("Document created successfully !");
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #7
0
        /// <summary>
        /// 添加勘察工作量统计表格
        /// </summary>
        /// <param name="_wordLoadStatistic">勘察工作量数据</param>
        /// <returns></returns>
        public MSWord.Table AddWorkLoadStatisticTable(StatisticWordLoad _wordLoadStatistic)
        {
            // 赋值工作量数组
            WorkLoadStatistic.amountList[0]  = "";
            WorkLoadStatistic.amountList[1]  = "";
            WorkLoadStatistic.amountList[2]  = _wordLoadStatistic.Borehole + "/" + _wordLoadStatistic.CountBorehole;
            WorkLoadStatistic.amountList[3]  = _wordLoadStatistic.Borehole + "/" + _wordLoadStatistic.CountBorehole;
            WorkLoadStatistic.amountList[4]  = _wordLoadStatistic.UndisturbedSample.ToString();
            WorkLoadStatistic.amountList[5]  = _wordLoadStatistic.DisturbedSample.ToString();
            WorkLoadStatistic.amountList[6]  = _wordLoadStatistic.NTestStandard.ToString();
            WorkLoadStatistic.amountList[7]  = _wordLoadStatistic.NTestN10.ToString();
            WorkLoadStatistic.amountList[8]  = _wordLoadStatistic.NTestN635.ToString();
            WorkLoadStatistic.amountList[9]  = _wordLoadStatistic.NTestN120.ToString();
            WorkLoadStatistic.amountList[10] = _wordLoadStatistic.CPT + "/" + _wordLoadStatistic.CountCPT;
            WorkLoadStatistic.amountList[11] = _wordLoadStatistic.RST.ToString();
            WorkLoadStatistic.amountList[12] = _wordLoadStatistic.Permeability.ToString();
            WorkLoadStatistic.amountList[13] = _wordLoadStatistic.GAT.ToString();
            WorkLoadStatistic.amountList[14] = "";

            // 填写表格标题
            Doc.Paragraphs.Last.Range.Text                = "表1 勘察工作量统计表";
            Doc.Paragraphs.Last.Range.Font.Bold           = 1;
            Doc.Paragraphs.Last.Range.Font.Size           = 12;
            App.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            object unite = MSWord.WdUnits.wdStory;

            App.Selection.EndKey(ref unite, ref Nothing);

            // 定义表格对象
            MSWord.Table table = Tables.Add(App.Selection.Range, 16, 5, ref Nothing, ref Nothing);

            // 填充行标题
            string[] rowheader = new string[] { "工 作 项 目", "单 位", "工作量", "备注" };
            for (int i = 2; i <= table.Columns.Count; i++)
            {
                table.Cell(1, i).Range.Text = rowheader[i - 2];
            }

            // 设置文档格式
            Doc.PageSetup.LeftMargin  = 50F;
            Doc.PageSetup.RightMargin = 50F;

            // 设置表格格式
            table.Select();
            App.Selection.Tables[1].Rows.Alignment = WdRowAlignment.wdAlignRowCenter;
            for (int i = 1; i <= table.Rows.Count; i++)
            {
                table.Rows[i].Range.Bold = 0;
            }
            table.Rows[1].Range.Bold = 1;
            table.Range.Font.Size    = 10.5F;
            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            table.Borders.OutsideLineStyle        = MSWord.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle         = MSWord.WdLineStyle.wdLineStyleSingle;
            float[] columnWidth = new float[] { 80, 120, 60, 60, 60 };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Columns[i].Width = columnWidth[i - 1];
            }

            // 填充工作量数据
            for (int i = 0; i < WorkLoadStatistic.amountList.Length; i++)
            {
                table.Cell(i + 2, 2).Range.Text = WorkLoadStatistic.typeList[i];
                table.Cell(i + 2, 3).Range.Text = WorkLoadStatistic.uniteList[i];
                table.Cell(i + 2, 4).Range.Text = WorkLoadStatistic.amountList[i];
                table.Cell(i + 2, 5).Range.Text = WorkLoadStatistic.remarkList[i];
            }

            // 填充第一列
            table.Cell(2, 1).Range.Text  = "测绘";
            table.Cell(4, 1).Range.Text  = "勘探";
            table.Cell(6, 1).Range.Text  = "取样";
            table.Cell(8, 1).Range.Text  = "原位测试";
            table.Cell(13, 1).Range.Text = "室内试验";

            // 删除空行
            int d = 0;

            for (int i = 0; i < 15; i++)
            {
                if (WorkLoadStatistic.amountList[i].ToString() == "0")
                {
                    table.Rows[i + 2 - d].Delete();
                    d++;
                }
            }


            // 合并单元格
            table.Cell(1, 1).Merge(table.Cell(1, 2));
            table.Cell(2, 1).Merge(table.Cell(3, 1));
            table.Cell(4, 1).Merge(table.Cell(5, 1));
            table.Cell(table.Rows.Count, 1).Merge(table.Cell(table.Rows.Count, 2));
            int[] mergeIndex = new int[3] {
                0, 0, 0
            };
            for (int i = 6; i <= table.Rows.Count - 1; i++)
            {
                if ((mergeIndex[0] == 0) && (table.Cell(i, 2).Range.Text.Contains("原状样") || table.Cell(i, 2).Range.Text.Contains("扰动样")))
                {
                    mergeIndex[0] = i;
                }
                if ((mergeIndex[1] == 0) && (table.Cell(i, 2).Range.Text.Contains("标准贯入试验") || table.Cell(i, 2).Range.Text.Contains("触探试验")))
                {
                    mergeIndex[1] = i;
                }
                if ((mergeIndex[2] == 0) && (table.Cell(i, 2).Range.Text.Contains("土工常规") || table.Cell(i, 2).Range.Text.Contains("室内渗透") || table.Cell(i, 2).Range.Text.Contains("颗粒分析") || table.Cell(i, 2).Range.Text.Contains("水质") || table.Cell(i, 2).Range.Text.Contains("击实")))
                {
                    mergeIndex[2] = i;
                }
            }
            for (int i = 0; i < 3; i++)
            {
                int startIndex = mergeIndex[i];
                int endIndex;
                if (i < 2)
                {
                    endIndex = mergeIndex[i + 1] - 1;
                }
                else
                {
                    endIndex = table.Rows.Count - 1;
                }
                if (startIndex == 0)
                {
                    continue;
                }
                if (startIndex != endIndex)
                {
                    table.Cell(startIndex, 1).Merge(table.Cell(endIndex, 1));
                }
            }

            // 返回
            return(table);
        }
예제 #8
0
        //Опис: Методот овозможува прибирање на сите податоци според избраните филтри од UI, задавање на изглед на самиот документ
        //Влезни параметри: успешно, неуспешно, дата од (за Логови), дата до (за Логови),корисник, провајдер, сервис
        public MemoryStream CreatingWordDocument(bool successfully, bool unsuccessfully, DateTime?fromDate,
                                                 DateTime?toDate, string consumer = "", string provider = "", string service = "")
        {
            var messageLogs = PrepareDataForReports(successfully, unsuccessfully, fromDate, toDate, consumer, provider, service);

            _logger.Info("CreatingWordDocument get message logs from PrepareDataForReports, count: " + messageLogs.Count);

            try
            {
                var winword = new Microsoft.Office.Interop.Word.Application();

                object   missing  = System.Reflection.Missing.Value;
                Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                document.PageSetup.TopMargin    = InchesToPoints(0.9f);
                document.PageSetup.BottomMargin = InchesToPoints(0.9f);
                document.PageSetup.LeftMargin   = InchesToPoints(0.9f);
                document.PageSetup.RightMargin  = InchesToPoints(0.9f);

                var macCultureInfo = CultureInfo.CreateSpecificCulture("mk-MK");
                foreach (Section section in document.Sections)
                {
                    //Get the header range and add the header details.
                    Range headerRange = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, WdFieldType.wdFieldPage);
                    headerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                    headerRange.Font.Name       = "Calibri";
                    headerRange.Font.ColorIndex = WdColorIndex.wdBlue;
                    headerRange.Font.Size       = 10;
                    headerRange.Text            = "Статистика за период " + fromDate.Value.ToString("dd.MM.yyyy", macCultureInfo) +
                                                  " - " + toDate.Value.ToString("dd.MM.yyyy", macCultureInfo);
                }
                foreach (Section wordSection in document.Sections)
                {
                    //Get the footer range and add the footer details.
                    Range footerRange = wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    footerRange.Font.ColorIndex           = WdColorIndex.wdDarkRed;
                    footerRange.Font.Size                 = 10;
                    footerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    footerRange.Text = "Детали за повикување на сервиси";
                }

                #region All services

                bool allServices = false;
                if (string.IsNullOrEmpty(service))
                {
                    allServices = true;
                    Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
                    para1.Range.Text = "Сервиси и вкупен број на повикувања:";
                    para1.Range.InsertParagraphAfter();
                }
                if (allServices)
                {
                    foreach (var messageLog in messageLogs)
                    {
                        foreach (var calledService in messageLog.ListServices)
                        {
                            Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
                            para1.Range.Text = "Сервис: " + calledService.ServiceName + ": " + calledService.TotalCalledTimes;
                            para1.Range.InsertParagraphAfter();
                        }
                    }
                }

                #endregion

                foreach (var messageLog in messageLogs)
                {
                    foreach (var services in messageLog.ListServices)
                    {
                        Paragraph para1         = document.Content.Paragraphs.Add(ref missing);
                        object    styleHeading1 = "Heading 1";
                        para1.Range.set_Style(ref styleHeading1);
                        para1.Range.Text = "Сервис: " + services.ServiceName;
                        // para1.SpaceBefore = InchesToPoints(0.6f);
                        para1.Range.InsertParagraphAfter();

                        //Add paragraph with Heading 2 style
                        Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
                        //object styleHeading2 = "Heading 3";
                        para2.Range.set_Style(WdBuiltinStyle.wdStyleIntenseReference);
                        para2.Range.Text = "Вкупен број на повикувања:" + services.TotalCalledTimes;
                        para2.Range.InsertParagraphAfter();

                        Paragraph para3 = document.Content.Paragraphs.Add(ref missing);
                        para3.Range.Text = Environment.NewLine + "Детали за повикување на сервисот од институции";
                        para3.Range.InsertParagraphAfter();

                        //Na baranje na MIOA, dokolku od UI se filtrira po uspeshni ili neuspeshni, vo dokument fajlot treba da gi dava samo tie koloni
                        int count = 0;
                        if (successfully || unsuccessfully)
                        {
                            count = 2;
                        }
                        if (!successfully && !unsuccessfully)
                        {
                            count = 4;
                        }

                        Table consumersTable = document.Tables.Add(para3.Range, services.ListConsumers.Count + 1, count, ref missing, ref missing);
                        consumersTable.Borders.Enable = 1;
                        consumersTable.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow);

                        //Adding header row
                        for (int i = 1; i <= count; i++)
                        {
                            consumersTable.Cell(1, i).Range.Font.Bold  = 1;
                            consumersTable.Cell(1, i).Range.Font.Name  = "Calibri";
                            consumersTable.Cell(1, i).Range.Font.Size  = 10;
                            consumersTable.Cell(1, i).Range.Font.Color = WdColor.wdColorGray75;
                            consumersTable.Cell(1, i).Shading.BackgroundPatternColor = WdColor.wdColorGray20;
                            consumersTable.Cell(1, i).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            consumersTable.Cell(1, i).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;

                            if (i == 1)
                            {
                                consumersTable.Cell(1, i).Range.Paragraphs.SpaceBefore = 7;
                                consumersTable.Cell(1, i).Range.Text = "Институција";
                            }
                            if (successfully)
                            {
                                if (i == 2)
                                {
                                    consumersTable.Cell(1, i).Range.Paragraphs.SpaceBefore = 7;
                                    consumersTable.Cell(1, i).Range.Text = "Успешни трансакции";
                                }
                            }
                            else if (unsuccessfully)
                            {
                                //ako nema uspeshni, togash kolonata za neuspeshni ima edna pozicija minus, sega e na pozicija 2
                                if (i == 2)
                                {
                                    consumersTable.Cell(1, i).Range.Paragraphs.SpaceBefore = 7;
                                    consumersTable.Cell(1, i).Range.Text = "Неуспешни трансакции";
                                }
                            }
                            else
                            {
                                if (i == 2)
                                {
                                    consumersTable.Cell(1, i).Range.Paragraphs.SpaceBefore = 7;
                                    consumersTable.Cell(1, i).Range.Text = "Успешни трансакции";
                                }
                                if (i == 3)
                                {
                                    consumersTable.Cell(1, i).Range.Paragraphs.SpaceBefore = 7;
                                    consumersTable.Cell(1, i).Range.Text = "Неуспешни трансакции";
                                }
                                if (i == 4)
                                {
                                    consumersTable.Cell(1, i).Range.Paragraphs.SpaceBefore = 7;
                                    consumersTable.Cell(1, i).Range.Text = "Вкупно трансакции";
                                }
                            }
                        }

                        //Adding the rest of the rows
                        for (int j = 0; j < services.ListConsumers.Count; j++)
                        {
                            consumersTable.Cell(j + 2, 1).Range.Text = services.ListConsumers[j].ConsumerName;

                            for (int k = 0; k < services.ListConsumers[j].ListProviders.Count; k++)
                            {
                                if (successfully)
                                {
                                    consumersTable.Cell(j + 2, 2).Range.Text = services.ListConsumers[j].ListProviders[k].SuccesfullCalls.toString();
                                }
                                else if (unsuccessfully)
                                {
                                    //ako nema uspeshni, togash kolonata neuspeshni ima edna pozicija minus, t.e sega e na pozicija 2
                                    consumersTable.Cell(j + 2, 2).Range.Text = services.ListConsumers[j].ListProviders[k].UnSuccesfullCalls.toString();
                                }
                                else
                                {
                                    consumersTable.Cell(j + 2, 2).Range.Text = services.ListConsumers[j].ListProviders[k].SuccesfullCalls.toString();
                                    consumersTable.Cell(j + 2, 3).Range.Text = services.ListConsumers[j].ListProviders[k].UnSuccesfullCalls.toString();
                                    consumersTable.Cell(j + 2, 4).Range.Text = services.ListConsumers[j].ListProviders[k].Count.toString();
                                }
                            }
                        }
                        Paragraph para4 = document.Content.Paragraphs.Add(ref missing);
                        para4.SpaceAfter = 7;
                        para4.Range.InsertParagraphAfter();
                    }
                }

                object filename = AppSettings.Get <string>("StatisticWordDocumentPath");
                document.SaveAs2(ref filename);
                document.Close(ref missing, ref missing, ref missing);
                winword.Quit(ref missing, ref missing, ref missing);
                var getDocument = File.ReadAllBytes(filename.toString());
                var stream      = new MemoryStream(getDocument);
                return(stream);
            }
            catch (Exception ex)
            {
                _logger.Error("Se sluci greska pri kreiranje na word dokumentot: ", ex);
                throw ex;
            }
        }
예제 #9
0
        private void button4_Click(object sender, EventArgs e)
        {
            Word.Application oWord = new Word.Application();

            string curDir = System.IO.Directory.GetCurrentDirectory();

            object шаблон = curDir + @"\протокол.dot";

            if (!System.IO.File.Exists(шаблон.ToString()))
            {
                MessageBox.Show("Нет файла " + шаблон.ToString());
                return;
            }

            try
            {
                Word.Document o = oWord.Documents.Add(Template: шаблон);


                Word.Table tab1 = o.Tables[1];
                Word.Table tab2 = o.Tables[2];
                oWord.Visible = true;


                tab1.Rows[1].Cells[1].Range.Text = "Протоколы результатов на дистанции " + клДистанция.наимен + " на " + клСлет.наимен;
                int j = 1;
                foreach (суда dRow in de.суда.Local)
                {
                    if (de.результаты.Local.Where(n => n.экипажи.судно == dRow.судно).Where(n => n.лучший > 0).Count(n => n.зачетный) > 0)
                    {
                        j++;
                        tab2.Rows.Add();
                        j++;
                        tab2.Rows[j].Cells[2].Range.Text = dRow.наимен;
                        tab2.Rows.Add();
                    }
                    foreach (результаты pRow in de.результаты.Local
                             .Where(n => n.экипажи.судно == dRow.судно)
                             .Where(n => n.лучший > 0).Where(n => n.зачетный).OrderBy(n => n.место))
                    {
                        j++;
                        tab2.Rows[j].Cells[1].Range.Text = pRow.номер.ToString();
                        tab2.Rows[j].Cells[2].Range.Text = pRow.клуб;
                        tab2.Rows[j].Cells[3].Range.Text = pRow.состав;
                        tab2.Rows[j].Cells[4].Range.Text = pRow.время_мин.ToString();
                        tab2.Rows[j].Cells[5].Range.Text = pRow.время_сек.ToString();
                        tab2.Rows[j].Cells[6].Range.Text = pRow.секунд.ToString();
                        tab2.Rows[j].Cells[7].Range.Text = pRow.штраф.ToString();
                        tab2.Rows[j].Cells[8].Range.Text = pRow.итог.ToString();
                        tab2.Rows[j].Cells[9].Range.Text = pRow.место.ToString();



                        tab2.Rows.Add();
                    }
                }


                oWord.Visible = true;
            }
            catch (Exception ex)
            {
                oWord.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
                oWord.Application.Quit(SaveChanges: false);
                MessageBox.Show("Сбой Word " + ex.Message);
            }
        }
예제 #10
0
        /// <summary>
        /// office导出word
        /// </summary>

        void MOExportWord()
        {
            try
            {
                string         primaryname    = "Office导出Word";
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.DefaultExt = ".docx";
                saveFileDialog.Filter     = "Word文档|*.doc;*.docx";
                // 是否自动添加扩展名
                saveFileDialog.AddExtension = true;
                // 文件已存在是否提示覆盖
                saveFileDialog.OverwritePrompt = true;
                // 提示输入的文件名无效
                saveFileDialog.CheckPathExists = true;
                // 文件初始名
                saveFileDialog.FileName = primaryname;
                if (saveFileDialog.ShowDialog() == true)
                {
                    // 文件保存的路径
                    object filename = saveFileDialog.FileName;
                    Object Nothing  = Missing.Value;


                    // 创建Word文档
                    Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
                    Microsoft.Office.Interop.Word.Document    WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                    // 添加页眉
                    // 设置右对齐
                    WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    WordApp.ActiveWindow.View.Type     = WdViewType.wdOutlineView;
                    WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;

                    WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("辽宁省沈阳市市政");


                    // 跳出页眉设置
                    WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;
                    // 设置文档的行间距
                    WordApp.Selection.ParagraphFormat.LineSpacing = 15f;

                    // 移动焦点并换行
                    object count = 20;
                    // 换一行
                    object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;
                    object unite  = Microsoft.Office.Interop.Word.WdUnits.wdStory;
                    // 移动焦点
                    // WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);
                    // 光标移动到未尾
                    WordApp.Selection.EndKey(ref unite, ref Nothing);

                    // 插入段落
                    Microsoft.Office.Interop.Word.Paragraph para = WordDoc.Content.Paragraphs.Add(ref Nothing);
                    int BigFontSize    = 14;
                    int NormalFontSize = 10;
                    int FontBoldTrue   = 2;
                    int FontBoldFalse  = 0;

                    // 加入测试模块内容
                    para.Alignment         = WdParagraphAlignment.wdAlignParagraphCenter;//对齐方式
                    para.Range.Text        = "公司注册信息表";
                    para.Range.Font.Size   = BigFontSize;
                    para.Range.Font.Bold   = FontBoldTrue;
                    para.Range.Font.Color  = WdColor.wdColorRed;
                    para.Range.Font.Italic = 0;
                    para.Range.InsertParagraphAfter();;

                    WordApp.Selection.EndKey(ref unite, ref Nothing);
                    para.Alignment        = WdParagraphAlignment.wdAlignParagraphCenter;//对齐方式
                    para.Range.Text       = "表1 所有注册公司信息";
                    para.Range.Font.Size  = NormalFontSize;
                    para.Range.Font.Bold  = FontBoldFalse;
                    para.Range.Font.Color = WdColor.wdColorBlack;
                    para.Range.InsertParagraphAfter();

                    WordApp.Selection.EndKey(ref unite, ref Nothing);

                    // 文档中创建表格
                    Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, CompanyData.Count, 5, ref Nothing, ref Nothing);
                    //设置表格样式
                    newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                    newTable.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                    // 垂直居中
                    WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                    // 水平居中
                    WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                    // 填充表格内容
                    newTable.Cell(1, 1).Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;
                    newTable.Cell(1, 1).Range.Text = "名称";
                    newTable.Cell(1, 2).Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;
                    newTable.Cell(1, 2).Range.Text = "地址";
                    newTable.Cell(1, 3).Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;
                    newTable.Cell(1, 3).Range.Text = "联系方式";
                    newTable.Cell(1, 4).Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;
                    newTable.Cell(1, 4).Range.Text = "法人";
                    newTable.Cell(1, 5).Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;
                    newTable.Cell(1, 5).Range.Text = "注册日期";

                    for (int j = 0; j < CompanyData.Count; j++)
                    {
                        newTable.Cell(j + 2, 1).Range.Text = CompanyData[j].Name;
                        newTable.Cell(j + 2, 2).Range.Text = CompanyData[j].Address;
                        newTable.Cell(j + 2, 3).Range.Text = CompanyData[j].Telephone;
                        newTable.Cell(j + 2, 4).Range.Text = CompanyData[j].LegalPerson;
                        newTable.Cell(j + 2, 5).Range.Text = CompanyData[j].RegistrationDate;
                    }
                    para.Range.InsertParagraphAfter();



                    // 文件保存
                    WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                    WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
                    WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

                    MessageBox.Show("生成报表成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示");
            }
        }
예제 #11
0
        //生成word文档
        void ExpWordByWord()
        {
            Word._Application app = new Word.Application();
            //表示System.Type信息中的缺少值
            object nothing = Type.Missing;

            try
            {
                //高考卡号
                string            strKaHao       = "";
                Entity.GaoKaoCard infoGaoKaoCard = DAL.GaoKaoCard.GaoKaoCardEntityGetByStudentId(userinfo.StudentId);
                if (infoGaoKaoCard != null)
                {
                    strKaHao = infoGaoKaoCard.KaHao;
                }
                //省份名称
                string strProvinceName = userinfo.ProvinceName;

                //读取模板文件
                object temp = System.Web.HttpContext.Current.Server.MapPath("~/CePing/职业兴趣模板.doc");//读取模板文件

                //建立一个基于摸版的文档
                Word._Document doc = app.Documents.Add(ref temp, ref nothing, ref nothing, ref nothing);
                //学生基本信息
                Word.Table tb1 = doc.Tables[1];
                if (tb1.Rows.Count == 4)
                {
                    //在指定单元格填值
                    //第1行
                    tb1.Cell(1, 2).Range.Text = userinfo.StudentName;
                    tb1.Cell(1, 4).Range.Text = (user.Sex == 1 ? "女" : "男");
                    //第2行
                    tb1.Cell(2, 2).Range.Text = user.SchoolName;
                    tb1.Cell(2, 4).Range.Text = (userinfo.KeLei == 1 ? "文史" : "理工");
                    //第3行
                    tb1.Cell(3, 2).Range.Text = strProvinceName;
                    tb1.Cell(3, 4).Range.Text = user.GKYear.ToString();
                    //第4行
                    tb1.Cell(4, 2).Range.Text = strKaHao;
                    tb1.Cell(4, 4).Range.Text = Basic.TypeConverter.StrToDateStr(DateTime.Now.ToString());
                }

                //插入图片
                Word.Table tb2              = doc.Tables[2];
                string     path             = AppDomain.CurrentDomain.BaseDirectory + ("CePing/ImgOfResult/Holland/") + user.StudentId + "_holland.jpg";
                string     FileName         = path;//@"C:\chart.jpeg";//图片所在路径
                object     LinkToFile       = false;
                object     SaveWithDocument = true;
                object     Anchor           = tb2.Range;
                doc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
                //doc.Application.ActiveDocument.InlineShapes[1].Width = 300f;//图片宽度
                //doc.Application.ActiveDocument.InlineShapes[1].Height = 200f;//图片高度

                //object readOnly = false;
                //object isVisible = false;

                //职业兴趣测评分类说明
                Word.Table tb3 = doc.Tables[3];
                if (tb3.Rows.Count == 7)
                {
                    //在指定单元格填值
                    //第2行 现实
                    tb3.Cell(2, 2).Range.Text = intReality.ToString();
                    tb3.Cell(2, 3).Range.Text = Level(intReality);
                    //第3行 研究
                    tb3.Cell(3, 2).Range.Text = intStudy.ToString();
                    tb3.Cell(3, 3).Range.Text = Level(intStudy);
                    //第4行 艺术
                    tb3.Cell(4, 2).Range.Text = intArt.ToString();
                    tb3.Cell(4, 3).Range.Text = Level(intArt);
                    //第5行 社会
                    tb3.Cell(5, 2).Range.Text = intSociety.ToString();
                    tb3.Cell(5, 3).Range.Text = Level(intSociety);
                    //第6行 企业
                    tb3.Cell(6, 2).Range.Text = intBusiness.ToString();
                    tb3.Cell(6, 3).Range.Text = Level(intBusiness);
                    //第7行 常规
                    tb3.Cell(7, 2).Range.Text = intTradition.ToString();
                    tb3.Cell(7, 3).Range.Text = Level(intTradition);
                }


                //模板中 占位符的替换
                Microsoft.Office.Interop.Word.Document oDoc = (Microsoft.Office.Interop.Word.Document)doc;
                bb();
                //根据你最强的兴趣,可见你的特点是
                ReplaceZF(oDoc, "@xqlx", strTeDian, Type.Missing);
                //你可能喜欢的专业
                for (int i = 0; i < arrTuiJianZhuanYe.Length; i++)
                {
                    ReplaceZF(oDoc, "@xihuanzhuanye" + i, arrTuiJianZhuanYe[i], Type.Missing);
                }
                if (arrTuiJianZhuanYe.Length < 6)
                {
                    for (int i = arrTuiJianZhuanYe.Length; i < 6; i++)
                    {
                        ReplaceZF(oDoc, "@xihuanzhuanye" + i, "", Type.Missing);
                    }
                }

                //不建议选择的专业范围
                for (int i = 0; i < arrBuTuiJianZhuanYe.Length; i++)
                {
                    ReplaceZF(oDoc, "@buxihuanzhuanye" + i, arrBuTuiJianZhuanYe[i], Type.Missing);
                }
                if (arrBuTuiJianZhuanYe.Length < 6)
                {
                    for (int i = arrBuTuiJianZhuanYe.Length; i < 6; i++)
                    {
                        ReplaceZF(oDoc, "@buxihuanzhuanye" + i, "", Type.Missing);
                    }
                }


                //保存到服务器
                object fileName = System.Web.HttpContext.Current.Server.MapPath("~/") + "CePing/ImgOfResult/Holland/" + strKaHao + "(" + userinfo.StudentName + "_" + userinfo.StudentId + ")" + "_职业兴趣测评.doc";//获取服务器路径
                //保存doc文档
                oDoc.SaveAs(ref fileName, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                            ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                            ref nothing, ref nothing, ref nothing);
                oDoc.Close(ref nothing, ref nothing, ref nothing);
                app.Quit(ref nothing, ref nothing, ref nothing);

                //输出word
                ExtWord(fileName.ToString(), "ts.doc");
            }
            catch (Exception ex)
            {
                //  resultMsg = "导出错误:" + ex.Message;
                app.Quit(ref nothing, ref nothing, ref nothing);
            }
        }
예제 #12
0
        private void AddBookToTable(Word.Table oTable, Book b, int id)
        {
            oTable.Cell(oTable.Rows.Count, 1).Range.Text = id.ToString();
            oTable.Cell(oTable.Rows.Count, 2).Range.Text = b.Author;
            oTable.Cell(oTable.Rows.Count, 3).Range.Text = b.Title;
            oTable.Cell(oTable.Rows.Count, 4).Range.Text = b.PlaceOfPublish;
            oTable.Cell(oTable.Rows.Count, 5).Range.Text = b.YearOfPublish;

            //oTable.Cell(oTable.Rows.Count, 6).Range.Text = oTable.Cell(oTable.Rows.Count, 6).Range.Text.Remove(1,1);
            string tmpN   = "";
            string tmpL   = "";
            string tmpNL  = "";
            string refnum = "";

            StringBuilder price        = new StringBuilder();
            int           summ         = 0;
            string        currency     = b.accNums_[0].Currency;
            bool          diffCurrency = false;
            string        trueCurrency = "";

            foreach (AccessionNumber num in b.accNums_)
            {
                if (num.IsWriteOff)
                {
                    tmpN += num.AccessionNum + "\r";
                    tmpL += num.AccessionLabel + "\r";

                    if (num.Price == -1)
                    {
                        price.AppendFormat("ошибка данных\r");//невозможно в число кастануть
                        diffCurrency = true;
                    }
                    else if (num.Price == -2)
                    {
                        price.AppendFormat("нет поля\r");
                        diffCurrency = true;
                    }
                    else
                    {
                        price.AppendFormat("{0} {1}\r", num.Price.ToString(), num.Currency);
                        trueCurrency = num.Currency;
                    }
                    summ += num.Price;
                    if (num.Price == 100)
                    {
                        summ += 1;
                        summ -= 1;
                    }
                    if (currency != num.Currency)
                    {
                        diffCurrency = true;
                    }
                }
                else
                {
                    tmpNL += num.AccessionNum + "\r";
                }
                if ((num.Fund == "O") && (num.IsWriteOff))
                {
                    refnum += b.ReferenceNumberOF + "\r";
                }
                if ((num.Fund == "A") && (num.IsWriteOff))
                {
                    refnum += b.ReferenceNumberAB + "\r";
                }
                if ((num.Fund == "R") && (num.IsWriteOff))
                {
                    refnum += b.ReferenceNumberR + "\r";
                }
            }
            tmpN   = (tmpN == string.Empty) ? tmpN : tmpN.Remove(tmpN.Length - 1);
            tmpL   = (tmpL == string.Empty) ? tmpL : tmpL.Remove(tmpL.Length - 1);
            tmpNL  = (tmpNL == string.Empty) ? tmpNL : tmpNL.Remove(tmpNL.Length - 1);
            refnum = (refnum == string.Empty) ? refnum : refnum.Remove(refnum.Length - 1);
            oTable.Cell(oTable.Rows.Count, 6).Range.Text = tmpN;
            //oTable.Cell(oTable.Rows.Count, 7).Range.Text = tmpL;
            oTable.Cell(oTable.Rows.Count, 8).Range.Text = tmpNL;
            //oTable.Cell(oTable.Rows.Count, 8).Range.Text = refnum;
            oTable.Cell(oTable.Rows.Count, 7).Range.Text = b.InvsLeftInFund.ToString();
            oTable.Cell(oTable.Rows.Count, 9).Range.Text = (price.Length == 0) ? price.ToString():price.ToString().Remove(price.Length - 1);
            if (diffCurrency)
            {
                oTable.Cell(oTable.Rows.Count, 11).Range.Text = "Невозможно подсчитать полную сумму.";
            }
            else
            {
                oTable.Cell(oTable.Rows.Count, 11).Range.Text = summ.ToString() + " " + trueCurrency;
            }
        }
예제 #13
0
        /// <summary>
        /// Создание таблицы
        /// </summary>
        /// <param name="list">Данные для заполнения</param>
        public async Task CreateTableAsync(List <Report> list)
        {
            await Task.Factory.StartNew(() =>
            {
                // Добавляем в документ несколько параграфов
                _wordDocument.Paragraphs.Add(Missing.Value);

                // Получаем ссылки на параграфы документа
                _wordParagraphs = _wordDocument.Paragraphs;
                // Будем работать со вторым параграфом
                _wordParagraph = _wordParagraphs[2];

                // Новая таблица
                Word.Table _wordTable = _wordDocument.Tables.Add(_wordParagraph.Range, list.Count + 2, 7,
                                                                 Word.WdDefaultTableBehavior.wdWord9TableBehavior, Word.WdAutoFitBehavior.wdAutoFitWindow);

                #region Ширина столбцов
                _wordTable.Columns[1].SetWidth(ColumnWidth: 28f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                _wordTable.Columns[2].SetWidth(ColumnWidth: 192f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                _wordTable.Columns[3].SetWidth(ColumnWidth: 28f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                _wordTable.Columns[4].SetWidth(ColumnWidth: 28f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                _wordTable.Columns[5].SetWidth(ColumnWidth: 28f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                _wordTable.Columns[6].SetWidth(ColumnWidth: 28f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                _wordTable.Columns[7].SetWidth(ColumnWidth: 135f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                #endregion

                #region Объединение ячеек
                // № п/п
                object begCell           = _wordTable.Cell(1, 1).Range.Start;
                object endCell           = _wordTable.Cell(2, 1).Range.End;
                Word.Range wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.Cells.Merge();

                // Критерии оценки
                begCell       = _wordTable.Cell(1, 2).Range.Start;
                endCell       = _wordTable.Cell(2, 2).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.Cells.Merge();

                // Шкала оценок
                begCell       = _wordTable.Cell(1, 3).Range.Start;
                endCell       = _wordTable.Cell(1, 6).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.Cells.Merge();

                // Краткое обоснование оценки
                begCell       = _wordTable.Cell(1, 4).Range.Start;
                endCell       = _wordTable.Cell(2, 7).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.Cells.Merge();
                #endregion

                #region Заполнение таблицы
                // Шапка
                Word.Range _wordCellRange = _wordTable.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       = "Краткое обоснование\nоценки";

                #if DEBUG
                // Видимость Word'а
                _wordApp.Visible = true;
                #endif

                // Виды оценок
                for (int i = 3; i < 7; i++)
                {
                    _wordCellRange      = _wordTable.Cell(2, i).Range;
                    _wordCellRange.Text = (i - 1).ToString();
                }

                for (int i = 0; i < list.Count; i++)
                {
                    // № п/п
                    _wordCellRange      = _wordTable.Cell(i + 3, 1).Range;
                    _wordCellRange.Text = list[i].Number.ToString();

                    // Критерии оценки
                    _wordCellRange      = _wordTable.Cell(i + 3, 2).Range;
                    _wordCellRange.Text = list[i].Name.ToString();

                    // 2
                    _wordCellRange      = _wordTable.Cell(i + 3, 3).Range;
                    _wordCellRange.Text = list[i].Mark2.ToString();

                    // 3
                    _wordCellRange      = _wordTable.Cell(i + 3, 4).Range;
                    _wordCellRange.Text = list[i].Mark3.ToString();

                    // 4
                    _wordCellRange      = _wordTable.Cell(i + 3, 5).Range;
                    _wordCellRange.Text = list[i].Mark4.ToString();

                    // 5
                    _wordCellRange      = _wordTable.Cell(i + 3, 6).Range;
                    _wordCellRange.Text = list[i].Mark5.ToString();

                    // Краткое обоснование оценки
                    _wordCellRange      = _wordTable.Cell(i + 3, 7).Range;
                    _wordCellRange.Text = list[i].Comment.ToString();
                }

                // Выравнивание
                begCell       = _wordTable.Cell(1, 1).Range.Start;
                endCell       = _wordTable.Cell(1, 4).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                _wordApp.Selection.Cells.VerticalAlignment   = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                begCell       = _wordTable.Cell(2, 3).Range.Start;
                endCell       = _wordTable.Cell(2, 6).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                _wordApp.Selection.Cells.VerticalAlignment   = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                begCell       = _wordTable.Cell(3, 3).Range.Start;
                endCell       = _wordTable.Cell(17, 6).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                _wordApp.Selection.Cells.VerticalAlignment   = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                begCell       = _wordTable.Cell(3, 1).Range.Start;
                endCell       = _wordTable.Cell(17, 1).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                _wordApp.Selection.Cells.VerticalAlignment   = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                #endregion

                // Меняем характеристики текста в таблице
                _wordTable.Range.Font.Color  = Word.WdColor.wdColorBlack;
                _wordTable.Range.Font.Size   = 12;
                _wordTable.Range.Font.Name   = "Times New Roman";
                _wordTable.Range.Font.Italic = 0;
                _wordTable.Range.Font.Bold   = 0;
            });
        }
예제 #14
0
        public void ToWord(IEnumerable <Mail> emails, int counter = 1)
        {
            try
            {
                //Create an instance for word app
                word = new WordInterop.Application
                {
                    //Set animation status for word application
                    ShowAnimation = false,
                    //Set status for word application is to be visible or not.
                    Visible       = false,
                    DisplayAlerts = WordInterop.WdAlertLevel.wdAlertsNone
                };

                //Create a missing variable for missing value
                object missing = System.Reflection.Missing.Value;

                //Use ConfigurationHelper class to read OutlookReportsAddIn.dll.config

                object filepath = Properties.Settings.Default.TemplatePath;

                //Create a new document
                document = word.Documents.Add(ref filepath, ref missing, ref missing, ref missing);

                //Add paragraph
                WordInterop.Paragraph parag = document.Content.Paragraphs.Add(ref missing);
                parag.Range.InsertParagraphAfter();

                //Create new table in paragraph
                WordInterop.Table table = document.Tables.Add(parag.Range, 3, 8, ref missing, ref missing);

                // Add border
                table.Borders.Enable = 1;

                // Add width for every colum
                table.Columns[1].Width = 28f;
                table.Columns[2].Width = 124f;
                table.Columns[3].Width = 180f;
                table.Columns[4].Width = 54f;
                table.Columns[5].Width = 44f;
                table.Columns[6].Width = 120f;
                table.Columns[7].Width = 100f;
                table.Columns[8].Width = 140f;

                // Table header
                table.Cell(1, 1).Range.Text = "№ п/п";
                table.Cell(1, 2).Range.Text = "Исходящий/входящий адрес электронной почты";
                table.Cell(1, 3).Range.Text = "Файл (КБ)";
                table.Cell(1, 4).Range.Text = "Категория срочности";
                table.Cell(1, 5).Range.Text = "Время приема/отправки";
                table.Cell(1, 6).Range.Text = "Кому (куда) адресована (адрес электронной почты)";
                table.Cell(1, 7).Range.Text = "Фамилия, инициалы и роспись дежурного по ШО";
                table.Cell(1, 8).Range.Text = "Примечание";
                table.Rows[1].Range.ParagraphFormat.Alignment = WordInterop.WdParagraphAlignment.wdAlignParagraphCenter;

                // Second row
                table.Cell(2, 1).Range.Text = "1";
                table.Cell(2, 2).Range.Text = "2";
                table.Cell(2, 3).Range.Text = "3";
                table.Cell(2, 4).Range.Text = "4";
                table.Cell(2, 5).Range.Text = "5";
                table.Cell(2, 6).Range.Text = "6";
                table.Cell(2, 7).Range.Text = "7";
                table.Cell(2, 8).Range.Text = "8";
                table.Rows[2].Range.ParagraphFormat.Alignment = WordInterop.WdParagraphAlignment.wdAlignParagraphCenter;

                int intRow = 3;

                // Retrieve the data and insert into new rows.
                object beforeRow = Type.Missing;

                var groupMailsByDate = emails.GroupBy(e => e.Date.ToShortDateString()).ToList();

                // Third row
                foreach (var mails in groupMailsByDate)
                {
                    var dateKey = mails.Key;
                    table.Rows.Add(ref beforeRow);
                    table.Cell(intRow, 3).Range.Text = dateKey;
                    table.Cell(intRow, 3).Range.ParagraphFormat.Alignment = WordInterop.WdParagraphAlignment.wdAlignParagraphCenter;

                    intRow++;

                    foreach (var mail in mails)
                    {
                        // Fourth row
                        table.Rows.Add(ref beforeRow);

                        table.Cell(intRow, 1).Range.Text = counter++.ToString();
                        table.Cell(intRow, 2).Range.Text = mail.SenderAddress;
                        table.Cell(intRow, 3).Range.Text = mail.Attachments;
                        table.Cell(intRow, 4).Range.Text = mail.Category;
                        table.Cell(intRow, 5).Range.Text = mail.Date.ToShortTimeString();
                        table.Cell(intRow, 6).Range.Text = mail.RecivedAddress;
                        table.Cell(intRow, 7).Range.Text = " ";
                        table.Cell(intRow, 8).Range.Text = mail.Subject;

                        intRow += 1;
                    }
                }
                SaveDialog(document);
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            finally
            {
                document.Close(null, null, null);
                word.Quit();
                if (document != null)
                {
                    Marshal.ReleaseComObject(document);
                }
            }
        }
예제 #15
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();
     }
 }
예제 #16
0
        private void CreateDocument()
        {
            try
            {
                //Create an instance for word app
                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

                //Set animation status for word application
                winword.ShowAnimation = false;

                //Set status for word application is to be visible or not.
                winword.Visible = false;



                //Create a missing variable for missing value
                object missing = System.Reflection.Missing.Value;

                //Create a new document
                Document document = winword.Documents.Add();

                document.PageSetup.Orientation = WdOrientation.wdOrientLandscape;//альбомная ориентация

                //Add header into the document
                //foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
                //{
                //    //Get the header range and add the header details.
                //    Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                //    headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                //    headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                //    headerRange.Font.Bold = 1;
                //    headerRange.Font.Size = 14;
                //    headerRange.Text = "Домашнее задание "+DocumentOptions[0]+" на закрепление пройденного материала";
                //}

                ////Add the footers into the document
                //foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                //{
                //    //Get the footer range and add the footer details.
                //    Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                //    footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
                //    footerRange.Font.Size = 10;
                //    footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                //    footerRange.Text = "Footer text goes here";
                //}

                Paragraph para1 = document.Content.Paragraphs.Add();
                para1.Range.Font.Size = 14;
                para1.Range.Font.Bold = 1;
                para1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                para1.Range.Text = "Домашнее задание " + DocumentOptions[0] + " на закрепление пройденного материала" + Environment.NewLine;
                para1.Range.InsertParagraphAfter();

                //adding text to document
                //document.Content.SetRange(0, 0);
                //document.Content.Text = "Дата " + DocumentOptions[1] + " Ф.И ребенка " + DocumentOptions[2] + " группа " + DocumentOptions[3] + " сад №" + DocumentOptions[4] + Environment.NewLine;

                //Add paragraph with Heading 1 style
                Paragraph para2 = document.Content.Paragraphs.Add();
                para2.Range.Font.Size = 12;
                para2.Range.Text      = "Дата " + DocumentOptions[1] + "     Ф.И ребенка " + DocumentOptions[2] + "      группа " + DocumentOptions[3] + "       сад №" + DocumentOptions[4] + Environment.NewLine;
                para2.Range.InsertParagraphAfter();

                ////Add paragraph with Heading 2 style
                //Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);

                //para2.Range.Text = "Para 2 text";
                //para2.Range.InsertParagraphAfter();

                //Create a 5X5 table and insert some dummy record
                Table firstTable = document.Tables.Add(para1.Range, 4, 6, ref missing, ref missing);

                firstTable.Rows[1].Cells[1].Range.Text = "Направления работы";
                firstTable.Rows[1].Cells[2].Range.Text = "Социализация (представления о себе и окружающем мире, игра)";
                firstTable.Rows[1].Cells[3].Range.Text = "Коммуникативная сфера(общение, речь)";
                firstTable.Rows[1].Cells[4].Range.Text = "Эмоционально – волевая сфера(эмоции, чувства, воля, мотивация)";
                firstTable.Rows[1].Cells[5].Range.Text = "Психические процессы(память, внимание, воображение, пространственное восприятие)";
                firstTable.Rows[1].Cells[6].Range.Text = "Сенсомоторная сфера(ощущения, восприятие, крупная и мелкая моторика)";


                firstTable.Rows[2].Cells[1].Range.Text = "Задачи";
                string str11 = "";
                for (int i = 0; i < 10; i++)
                {
                    if (Task_Massiv[i, 0] != null)
                    {
                        str11 += Task_Massiv[i, 0] + "\n";
                    }
                    else
                    {
                        i = 10;
                    }
                }
                string str12 = "";
                for (int i = 0; i < 10; i++)
                {
                    if (Task_Massiv[i, 1] != null)
                    {
                        str12 += Task_Massiv[i, 1] + "\n";
                    }
                    else
                    {
                        i = 10;
                    }
                }
                string str13 = "";
                for (int i = 0; i < 10; i++)
                {
                    if (Task_Massiv[i, 2] != null)
                    {
                        str13 += Task_Massiv[i, 2] + "\n";
                    }
                    else
                    {
                        i = 10;
                    }
                }
                string str14 = "";
                for (int i = 0; i < 10; i++)
                {
                    if (Task_Massiv[i, 3] != null)
                    {
                        str14 += Task_Massiv[i, 3] + "\n";
                    }
                    else
                    {
                        i = 10;
                    }
                }
                string str15 = "";
                for (int i = 0; i < 10; i++)
                {
                    if (Task_Massiv[i, 4] != null)
                    {
                        str15 += Task_Massiv[i, 4] + "\n";
                    }
                    else
                    {
                        i = 10;
                    }
                }
                firstTable.Rows[2].Cells[2].Range.Text = str11; /*Task_Massiv[0,0]+"\n"+ Task_Massiv[1,0]+ "\n" + Task_Massiv[2,0]+ "\n" + Task_Massiv[3,0] + "\n" + Task_Massiv[4,0] + "\n" + Task_Massiv[5,0] + "\n" + Task_Massiv[6,0] + "\n" + Task_Massiv[7,0] + "\n" + Task_Massiv[8, 0] + "\n" + Task_Massiv[9, 0];*/
                firstTable.Rows[2].Cells[3].Range.Text = str12; /*Task_Massiv[0, 1] + "\n" + Task_Massiv[1, 1] + "\n" + Task_Massiv[2, 1] + "\n" + Task_Massiv[3, 1] + "\n" + Task_Massiv[4, 1] + "\n" + Task_Massiv[5, 1] + "\n" + Task_Massiv[6, 1] + "\n" + Task_Massiv[7, 1] + "\n" + Task_Massiv[8, 1] + "\n" + Task_Massiv[9, 1];*/
                firstTable.Rows[2].Cells[4].Range.Text = str13; /*Task_Massiv[0, 2] + "\n" + Task_Massiv[1, 2] + "\n" + Task_Massiv[2, 2] + "\n" + Task_Massiv[3, 2] + "\n" + Task_Massiv[4, 2] + "\n" + Task_Massiv[5, 2] + "\n" + Task_Massiv[6, 2] + "\n" + Task_Massiv[7, 2] + "\n" + Task_Massiv[8, 2] + "\n" + Task_Massiv[9, 2];*/
                firstTable.Rows[2].Cells[5].Range.Text = str14; /*Task_Massiv[0, 3] + "\n" + Task_Massiv[1, 3] + "\n" + Task_Massiv[2, 3] + "\n" + Task_Massiv[3, 3] + "\n" + Task_Massiv[4, 3] + "\n" + Task_Massiv[5, 3] + "\n" + Task_Massiv[6, 3] + "\n" + Task_Massiv[7, 3] + "\n" + Task_Massiv[8, 3] + "\n" + Task_Massiv[9, 3];*/
                firstTable.Rows[2].Cells[6].Range.Text = str15; /*Task_Massiv[0, 4] + "\n" + Task_Massiv[1, 4] + "\n" + Task_Massiv[2, 4] + "\n" + Task_Massiv[3, 4] + "\n" + Task_Massiv[4, 4] + "\n" + Task_Massiv[5, 4] + "\n" + Task_Massiv[6, 4] + "\n" + Task_Massiv[7, 4] + "\n" + Task_Massiv[8, 4] + "\n" + Task_Massiv[9, 4];*/


                string str21 = "";
                for (int i = 0; i < 10; i++)
                {
                    if (Game_Massiv[i, 0] != null)
                    {
                        str21 += Game_Massiv[i, 0] + "\n";
                    }
                    else
                    {
                        i = 10;
                    }
                }
                string str22 = "";
                for (int i = 0; i < 10; i++)
                {
                    if (Game_Massiv[i, 1] != null)
                    {
                        str22 += Game_Massiv[i, 1] + "\n";
                    }
                    else
                    {
                        i = 10;
                    }
                }
                string str23 = "";
                for (int i = 0; i < 10; i++)
                {
                    if (Game_Massiv[i, 2] != null)
                    {
                        str23 += Game_Massiv[i, 2] + "\n";
                    }
                    else
                    {
                        i = 10;
                    }
                }
                string str24 = "";
                for (int i = 0; i < 10; i++)
                {
                    if (Game_Massiv[i, 3] != null)
                    {
                        str24 += Game_Massiv[i, 3] + "\n";
                    }
                    else
                    {
                        i = 10;
                    }
                }
                string str25 = "";
                for (int i = 0; i < 10; i++)
                {
                    if (Game_Massiv[i, 4] != null)
                    {
                        str25 += Game_Massiv[i, 4] + "\n";
                    }
                    else
                    {
                        i = 10;
                    }
                }


                firstTable.Rows[3].Cells[1].Range.Text = "Игры, задания";
                firstTable.Rows[3].Cells[2].Range.Text = str21; /*Game_Massiv[0, 0] + "\n" + Game_Massiv[1, 0] + "\n" + Game_Massiv[2, 0] + "\n" + Game_Massiv[3, 0] + "\n" + Game_Massiv[4, 0] + "\n" + Game_Massiv[5, 0] + "\n" + Game_Massiv[6, 0] + "\n" + Game_Massiv[7, 0] + "\n" + Game_Massiv[8, 0] + "\n" + Game_Massiv[9, 0];*/
                firstTable.Rows[3].Cells[3].Range.Text = str22; /*Game_Massiv[0, 1] + "\n" + Game_Massiv[1, 1] + "\n" + Game_Massiv[2, 1] + "\n" + Game_Massiv[3, 1] + "\n" + Game_Massiv[4, 1] + "\n" + Game_Massiv[5, 1] + "\n" + Game_Massiv[6, 1] + "\n" + Game_Massiv[7, 1] + "\n" + Game_Massiv[8, 1] + "\n" + Game_Massiv[9, 1];*/
                firstTable.Rows[3].Cells[4].Range.Text = str23; /*Game_Massiv[0, 2] + "\n" + Game_Massiv[1, 2] + "\n" + Game_Massiv[2, 2] + "\n" + Game_Massiv[3, 2] + "\n" + Game_Massiv[4, 2] + "\n" + Game_Massiv[5, 2] + "\n" + Game_Massiv[6, 2] + "\n" + Game_Massiv[7, 2] + "\n" + Game_Massiv[8, 2] + "\n" + Game_Massiv[9, 2];*/
                firstTable.Rows[3].Cells[5].Range.Text = str24; /*Game_Massiv[0, 3] + "\n" + Game_Massiv[1, 3] + "\n" + Game_Massiv[2, 3] + "\n" + Game_Massiv[3, 3] + "\n" + Game_Massiv[4, 3] + "\n" + Game_Massiv[5, 3] + "\n" + Game_Massiv[6, 3] + "\n" + Game_Massiv[7, 3] + "\n" + Game_Massiv[8, 3] + "\n" + Game_Massiv[9, 3];*/
                firstTable.Rows[3].Cells[6].Range.Text = str25; /*Game_Massiv[0, 4] + "\n" + Game_Massiv[1, 4] + "\n" + Game_Massiv[2, 4] + "\n" + Game_Massiv[3, 4] + "\n" + Game_Massiv[4, 4] + "\n" + Game_Massiv[5, 4] + "\n" + Game_Massiv[6, 4] + "\n" + Game_Massiv[7, 4] + "\n" + Game_Massiv[8, 4] + "\n" + Game_Massiv[9, 4];*/



                firstTable.Rows[4].Height = 200;
                firstTable.Rows[4].Cells[1].Range.Text = "Результат, примечания* ";

                firstTable.Borders.Enable = 1;

                //foreach (Row row in firstTable.Rows)
                //{
                //    foreach (Cell cell in row.Cells)
                //    {


                //        //Header row
                //        if (cell.RowIndex == 1)
                //        {
                //            cell.Range.Text = "Column " + cell.ColumnIndex.ToString();
                //            cell.Range.Font.Bold = 1;
                //            //other format properties goes here
                //            cell.Range.Font.Name = "verdana";
                //            cell.Range.Font.Size = 10;
                //            //cell.Range.Font.ColorIndex = WdColorIndex.wdGray25;
                //            cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                //            //Center alignment for the Header cells
                //            cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                //            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;

                //        }
                //        //Data row
                //        else
                //        {
                //            cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString();
                //        }
                //    }
                //}


                Paragraph para3 = document.Content.Paragraphs.Add();
                para3.Range.Font.Size = 12;
                if (DocumentOptions[0] == "для родителей")
                {
                    para3.Range.Text = "* Заполняется родителями (выполняет с легкостью/ справляется/ возникают незначительные затруднения/ возникли значительные трудности/ отказ от выполнения задания/  не выполнили задания; в примечаниях желательно написать в чем конкретно возникали трудности)" + Environment.NewLine;
                }
                else
                {
                    para3.Range.Text = "* Заполняется воспитателями (выполняет с легкостью/ справляется/ возникают незначительные затруднения/ возникли значительные трудности/ отказ от выполнения задания/  не выполнили задания; в примечаниях желательно написать в чем конкретно возникали трудности)" + Environment.NewLine;
                }
                para3.Range.InsertParagraphAfter();
                //Save the document


                string filename = Directory.GetCurrentDirectory() + "/files/" + DocumentOptions[2] + ".docx";
                if (File.Exists(filename))
                {
                    document.SaveAs2(filename);
                    document.Close(ref missing, ref missing, ref missing);
                    document = null;
                    winword.Quit(ref missing, ref missing, ref missing);
                    winword = null;
                    MessageBox.Show("Document created successfully !");
                }
                else
                {
                    filename = Directory.GetCurrentDirectory() + "/files/" + DocumentOptions[2] + DocumentOptions[1] + ".docx";
                    document.SaveAs2(filename);
                    document.Close(ref missing, ref missing, ref missing);
                    document = null;
                    winword.Quit(ref missing, ref missing, ref missing);
                    winword = null;
                    MessageBox.Show("Document created successfully !");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #17
0
 public bool GetTable(int count)
 {
     try
     {
         var table = wordDocument.Tables[count];
         tables = table;
         return true;
     }
     catch
     {
         MessageBox.Show(@"Не получилось выявить таблицу");
         return false;
     }
 }
        private void FormatReport()
        {
            var    wordApp    = new Word.Application();
            string reportPath = "";

            try
            {
                reportPath =
                    Application.StartupPath + @"\forecast" + "_" +
                    DateTime.Now.Year + "_" +
                    DateTime.Now.Month + "_" +
                    DateTime.Now.Day + "_" +
                    DateTime.Now.Hour + "_" +
                    DateTime.Now.Minute + "_" +
                    DateTime.Now.Second +
                    ".docx";
                File.Copy(_reportPathGoodProfit, reportPath);

                wordApp.Visible = false;
                var wordDoc = wordApp.Documents.Open(reportPath);

                ReplaceWordStub("{title}", "Запрос на пополнение запасов товаров", wordDoc);
                ReplaceWordStub("{date_to}", DateTime.Today.Date.ToShortDateString(), wordDoc);

                DateTime today = DateTime.Today.Date;
                string   res   = "";
                if (cbxOptions.SelectedIndex == 0)
                {
                    res = today.AddMonths(-1).ToShortDateString();
                }
                if (cbxOptions.SelectedIndex == 1)
                {
                    res = today.AddMonths(-3).ToShortDateString();
                }
                else if (cbxOptions.SelectedIndex == 2)
                {
                    res = today.AddMonths(-12).ToShortDateString();
                }
                else if (cbxOptions.SelectedIndex == 3)
                {
                    res = "начало работы";
                }
                ReplaceWordStub("{date_from}", res, wordDoc);

                wordDoc.Save();

                Word.Table table = wordDoc.Tables[1];
                int        cols  = dgvMain.ColumnCount;
                int        rows  = dgvMain.RowCount;
                for (int i = 0; i < cols; i++)
                {
                    table.Rows[1].Cells[i + 1].Range.Text = dgvMain.Columns[i].HeaderText;
                }
                table.Rows[1].Cells[cols + 1].Range.Text = "Кол-во для пополнения запасов";
                table.Rows.Add();
                for (int i = 0, row = 0; i < rows; i++)
                {
                    if (Convert.ToInt32(dgvMain.Rows[i].Cells[2].Value) - Convert.ToInt32(dgvMain.Rows[i].Cells[1].Value) > 0)
                    {
                        continue;
                    }

                    for (int j = 0; j < cols; j++)
                    {
                        table.Rows[row + 2].Cells[j + 1].Range.Text = dgvMain.Rows[i].Cells[j].Value.ToString();
                    }
                    table.Rows[row + 2].Cells[cols + 1].Range.Text =
                        Convert.ToInt32(dgvMain.Rows[i].Cells[2].Value) - Convert.ToInt32(dgvMain.Rows[i].Cells[1].Value) >= 0 ?
                        "0" :
                        (Convert.ToInt32(dgvMain.Rows[i].Cells[1].Value) - Convert.ToInt32(dgvMain.Rows[i].Cells[2].Value)).ToString();
                    row++;
                    if (i != rows - 1)
                    {
                        table.Rows.Add();
                    }
                }

                object missing = System.Reflection.Missing.Value;
                wordDoc.Save();
                wordApp.Visible = true;
            }
            catch (Exception e)
            {
                MessageBox.Show("Не удалось сформировать отчет" + Environment.NewLine + e.Message,
                                "Ошибка",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }
예제 #19
0
        private void button1_Click(object sender, EventArgs e)
        {
            //запишем название льготной категории
            льготнаяКатегорияТекст = this.cmbЛьготнаяКатегория.Text.Trim();

            int iCountЛьготник = Convert.ToInt32(ТаблицаБД.GetTable("select Count(*) from Льготник", ConnectionDB.ConnectionString(), "Льготник").Rows[0][0]);

            if (iCountЛьготник == 0)
            {
                MessageBox.Show("Нет данных по льготнику");
                this.Close();
                return;
            }


            string sCon = ConnectionDB.ConnectionString();

            this.dtEnd.Value = this.dtEnd.Value.AddDays(1);
            //  this.dtStart.Value = this.dtStart.Value.AddDays(-1);


            string endYear = this.dtEnd.Value.Year.ToString();
            //отними 1
            //string endDay = this.dtEnd.Value.Day.ToString();
            string endDay   = Convert.ToString(this.dtEnd.Value.Day);
            string endMonth = this.dtEnd.Value.Month.ToString();

            string strYear = this.dtStart.Value.Year.ToString();
            //прибавим 1
            //string strDay = this.dtStart.Value.Day.ToString();
            string strDay   = Convert.ToString(this.dtStart.Value.Day);
            string strMonth = this.dtStart.Value.Month.ToString();

            string endДата = "#" + endMonth + "/" + endDay + "/" + endYear + "#";
            string strДата = "#" + strMonth + "/" + strDay + "/" + strYear + "#";

            this.dtEnd.Value = this.dtEnd.Value.AddDays(-1);

            //#02/05/2013#

            //======================================Рабочая версия реест выполненных договоров
            //string queryReestr = "SELECT ЛьготнаяКатегория.ЛьготнаяКатегория as 'Льготная категория', Льготник.Фамилия, Льготник.Имя, Льготник.Отчество, Договор.ДатаДоговора, Льготник.СерияДокумента, Льготник.НомерДокумента, Льготник.ДатаВыдачиДокумента,Sum(АктВыполнненныхРабот.Сумма) AS [Сумма], АктВыполнненныхРабот.НомерАкта, Договор.НомерДоговора, АктВыполнненныхРабот.ДатаПодписания " +
            //         "FROM (ЛьготнаяКатегория INNER JOIN Льготник ON ЛьготнаяКатегория.id_льготнойКатегории = Льготник.id_льготнойКатегории) INNER JOIN (Договор INNER JOIN АктВыполнненныхРабот ON Договор.id_договор = АктВыполнненныхРабот.id_договор) ON Льготник.id_льготник = Договор.id_льготник " +
            //         "WHERE (((ЛьготнаяКатегория.ЛьготнаяКатегория)='" + this.cmbЛьготнаяКатегория.Text + "')AND (Договор.ФлагНаличияАкта = True)) " +
            //         "GROUP BY ЛьготнаяКатегория.ЛьготнаяКатегория, Льготник.Фамилия, Льготник.Имя, Льготник.Отчество, Договор.ДатаДоговора, Льготник.СерияДокумента, Льготник.НомерДокумента, АктВыполнненныхРабот.НомерАкта, Договор.НомерДоговора, АктВыполнненныхРабот.ДатаПодписания, АктВыполнненныхРабот.ДатаПодписания, Льготник.ДатаВыдачиДокумента " +
            //         "HAVING (((АктВыполнненныхРабот.ДатаПодписания)>= " + strДата + " And (АктВыполнненныхРабот.ДатаПодписания)< " + endДата + "))";


            //======================================Рабочая версия реестра с суммами в договорах==============
            if (this.еестрЗаключенныхДоговоров == true)
            {                                                                                                                                                                                                                                                                                                                                                                                                            //, Льготник.СНИЛС
                queryReestr = "SELECT ЛьготнаяКатегория.ЛьготнаяКатегория AS ['Льготная категория'], Льготник.Фамилия, Льготник.Имя, Льготник.Отчество, Договор.ДатаДоговора, Льготник.СерияДокумента, Льготник.НомерДокумента, Льготник.ДатаВыдачиДокумента, АктВыполнненныхРабот.НомерАкта, Договор.НомерДоговора,АктВыполнненныхРабот.id_акт, АктВыполнненныхРабот.ДатаПодписания,АктВыполнненныхРабот.НомерПоПеречню, Sum(УслугиПоДоговору.Сумма) AS Сумма " +
                              "FROM (ЛьготнаяКатегория INNER JOIN Льготник ON ЛьготнаяКатегория.id_льготнойКатегории = Льготник.id_льготнойКатегории) INNER JOIN ((Договор INNER JOIN АктВыполнненныхРабот ON Договор.id_договор = АктВыполнненныхРабот.id_договор) INNER JOIN УслугиПоДоговору ON Договор.id_договор = УслугиПоДоговору.id_договор) ON Льготник.id_льготник = Договор.id_льготник " +
                              "WHERE (((ЛьготнаяКатегория.ЛьготнаяКатегория)='" + this.cmbЛьготнаяКатегория.Text + "') AND ((Договор.ФлагНаличияАкта)=True)) " +
                              "GROUP BY ЛьготнаяКатегория.ЛьготнаяКатегория, Льготник.Фамилия, Льготник.Имя, Льготник.Отчество, Договор.ДатаДоговора, Льготник.СерияДокумента, Льготник.НомерДокумента, Льготник.ДатаВыдачиДокумента, АктВыполнненныхРабот.НомерАкта, Договор.НомерДоговора, АктВыполнненныхРабот.ДатаПодписания,АктВыполнненныхРабот.id_акт,АктВыполнненныхРабот.НомерПоПеречню " + //,Льготник.СНИЛС
                              "HAVING (((АктВыполнненныхРабот.ДатаПодписания)>= " + strДата + " And (АктВыполнненныхРабот.ДатаПодписания)< " + endДата + "))";                                                                                                                                                                                                                                       //AND (Договор.ФлагНаличияАкта <> True)
            }

            //Выводим реестр заключённых договоров
            if (this.еестрЗаключенныхДоговоров == false)
            {                                                                                                                                                                                                                                                                       //, Льготник.СНИЛС
                queryReestr = "SELECT ЛьготнаяКатегория.ЛьготнаяКатегория AS ['Льготная категория'], Льготник.Фамилия, Льготник.Имя, Льготник.Отчество, Договор.ДатаДоговора, Льготник.СерияДокумента, Льготник.НомерДокумента, Льготник.ДатаВыдачиДокумента, Договор.НомерДоговора, Sum(УслугиПоДоговору.Сумма) AS Сумма " +
                              "FROM (ЛьготнаяКатегория INNER JOIN Льготник ON ЛьготнаяКатегория.id_льготнойКатегории = Льготник.id_льготнойКатегории) INNER JOIN (Договор INNER JOIN УслугиПоДоговору ON Договор.id_договор = УслугиПоДоговору.id_договор) ON Льготник.id_льготник = Договор.id_льготник " +
                              "WHERE (((Договор.ФлагНаличияАкта)=False) and (ЛьготнаяКатегория.ЛьготнаяКатегория)='" + this.cmbЛьготнаяКатегория.Text + "') " +
                              "GROUP BY ЛьготнаяКатегория.ЛьготнаяКатегория, Льготник.Фамилия, Льготник.Имя, Льготник.Отчество, Договор.ДатаДоговора, Льготник.СерияДокумента, Льготник.НомерДокумента, Льготник.ДатаВыдачиДокумента, Договор.НомерДоговора " +//, Льготник.СНИЛС
                              "HAVING (([Договор].[ДатаДоговора]>=" + strДата + " And [Договор].[ДатаДоговора]<" + endДата + "));";
            }

            List <еестр> list = new List <еестр>();

            if (this.еестрЗаключенныхДоговоров == true)
            {
                //List<Реестр> list = new List<Реестр>();


                //сформируем данные для рееста
                DataTable dt = ТаблицаБД.GetTable(queryReestr, sCon, "Реестр");

                int iCount = 1;

                decimal sumCount = 0m;

                //заполним list
                foreach (DataRow row in dt.Rows)
                {
                    еестр str = new  еестр();
                    str.Id_акт = Convert.ToInt32(row["id_акт"]);

                    str.НомерПорядковый = iCount.ToString();

                    string фамилия = row["Фамилия"].ToString();

                    //if (фамилия == "Якямсева")
                    //{
                    //    string asdasd = "test";
                    //}
                    string имя      = row["Имя"].ToString();
                    string отчество = row["Отчество"].ToString();

                    str.ФИО = фамилия + " " + имя + " " + отчество;
                    str.НомерДатаДоговора = row["НомерДоговора"].ToString() + " " + Convert.ToDateTime(row["ДатаДоговора"]).ToShortDateString();

                    if (this.еестрЗаключенныхДоговоров == true)
                    {
                        str.НомерДатаАкта = row["НомерАкта"].ToString() + " " + Convert.ToDateTime(row["ДатаПодписания"]).ToShortDateString();
                    }

                    if (row["НомерПоПеречню"].ToString() == "True")
                    {
                        str.ФлагАктРеестр = true;
                    }
                    else
                    {
                        str.ФлагАктРеестр = false;
                    }

                    str.СерияДатаВыдачиДокумента = row["СерияДокумента"].ToString() + " " + row["НомерДокумента"].ToString() + " " + Convert.ToDateTime(row["ДатаВыдачиДокумента"]).ToShortDateString();
                    // str.SNILS = row["СНИЛС"].ToString();
                    str.СтоимсотьУслуги = row["Сумма"].ToString();

                    sumCount = sumCount + Convert.ToDecimal(str.СтоимсотьУслуги);

                    list.Add(str);
                    iCount++;
                }
            }

            if (this.еестрЗаключенныхДоговоров == false)
            {
                //queryReestr = "SELECT ЛьготнаяКатегория.ЛьготнаяКатегория AS ['Льготная категория'], Льготник.Фамилия, Льготник.Имя, Льготник.Отчество, Договор.ДатаДоговора, Льготник.СерияДокумента, Льготник.НомерДокумента, Льготник.ДатаВыдачиДокумента, Договор.НомерДоговора, Sum(УслугиПоДоговору.Сумма) AS Сумма " +
                //              "FROM (ЛьготнаяКатегория INNER JOIN Льготник ON ЛьготнаяКатегория.id_льготнойКатегории = Льготник.id_льготнойКатегории) INNER JOIN (Договор INNER JOIN УслугиПоДоговору ON Договор.id_договор = УслугиПоДоговору.id_договор) ON Льготник.id_льготник = Договор.id_льготник " +
                //              "WHERE (((Договор.ФлагНаличияАкта)=False) and (ЛьготнаяКатегория.ЛьготнаяКатегория)='" + this.cmbЛьготнаяКатегория.Text + "')  AND ((Договор.ДатаДоговора) is NULL)" +
                //              "GROUP BY ЛьготнаяКатегория.ЛьготнаяКатегория, Льготник.Фамилия, Льготник.Имя, Льготник.Отчество, Договор.ДатаДоговора, Льготник.СерияДокумента, Льготник.НомерДокумента, Льготник.ДатаВыдачиДокумента, Договор.НомерДоговора ";// +
                //              //"HAVING (([Договор].[ДатаДоговора]>=" + strДата + " And [Договор].[ДатаДоговора]<" + endДата + "));"; // Было закоментировано

                //сформируем данные для рееста
                DataTable dt_null = ТаблицаБД.GetTable(queryReestr, sCon, "Реестр");

                //формируем шапку таблицы


                //List<Реестр> list = new List<Реестр>(); // ТЕСТ

                еестр реестр = new  еестр();
                реестр.НомерПорядковый = "№ п.п";

                реестр.ФИО = "Ф.И.О.";
                реестр.НомерДатаДоговора = "№ и дата договора на предоставление услуг";

                реестр.НомерДатаАкта            = "№ и дата акта выполненных работ";
                реестр.СерияДатаВыдачиДокумента = "Серия, № и дата документа о праве на льготу";
                // реестр.SNILS = "СНИЛС";
                реестр.СтоимсотьУслуги = "Стоимость услуги, руб";
                list.Add(реестр);

                //Счётчик
                int     iCount   = 1;
                decimal sumCount = 0m;

                //заполним list
                foreach (DataRow row in dt_null.Rows)
                {
                    еестр str = new  еестр();
                    str.НомерПорядковый = iCount.ToString();

                    string фамилия = row["Фамилия"].ToString();

                    //if (фамилия == "Жирнова")
                    //{
                    //   string asdasd = "test";
                    //}

                    string имя      = row["Имя"].ToString();
                    string отчество = row["Отчество"].ToString();

                    str.ФИО = фамилия + " " + имя + " " + отчество;

                    if (this.еестрЗаключенныхДоговоров == false)
                    {
                        str.НомерДатаДоговора = row["НомерДоговора"].ToString() + " " + Convert.ToDateTime(row["ДатаДоговора"]).ToShortDateString();
                    }
                    else
                    {
                        str.НомерДатаДоговора = row["НомерДоговора"].ToString();
                    }

                    if (this.еестрЗаключенныхДоговоров == true)
                    {
                        str.НомерДатаАкта = row["НомерАкта"].ToString() + " " + Convert.ToDateTime(row["ДатаПодписания"]).ToShortDateString();
                    }

                    str.СерияДатаВыдачиДокумента = row["СерияДокумента"].ToString() + " " + row["НомерДокумента"].ToString() + " " + Convert.ToDateTime(row["ДатаВыдачиДокумента"]).ToShortDateString();
                    // str.SNILS = row["СНИЛС"].ToString();
                    str.СтоимсотьУслуги = row["Сумма"].ToString();

                    sumCount = sumCount + Convert.ToDecimal(str.СтоимсотьУслуги);

                    list.Add(str);
                    iCount++;
                }

                // Подсчитаем строку ИТОГО.
                decimal sumCountPrint = sumCount;

                еестр strCount = new  еестр();
                strCount.ФИО             = "Итого :";
                strCount.СтоимсотьУслуги = Math.Round(sumCount, 2).ToString("c");

                list.Add(strCount);

                //Вставим WORD
                string fNameP = "Реестр " + this.dtStart.Value.ToShortDateString().Replace('.', '_') + " " + this.dtEnd.Value.ToShortDateString().Replace('.', '_');


                try
                {
                    //Скопируем шаблон в папку Документы
                    FileInfo fn = new FileInfo(System.Windows.Forms.Application.StartupPath + @"\Шаблон\Реестр.doc");
                    fn.CopyTo(System.Windows.Forms.Application.StartupPath + @"\Документы\" + fNameP + ".doc", true);
                }
                catch
                {
                    MessageBox.Show("Документ с таки именем уже существует");
                }

                string filName = System.Windows.Forms.Application.StartupPath + @"\Документы\" + fNameP + ".doc";

                //Создаём новый Word.Application
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

                //Загружаем документ
                Microsoft.Office.Interop.Word.Document doc = null;

                object fileName   = filName;
                object falseValue = false;
                object trueValue  = true;
                object missing    = Type.Missing;

                doc = app.Documents.Open(ref fileName, ref missing, ref trueValue,
                                         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);

                //зададим левый отступ
                doc.PageSetup.LeftMargin = 40f;


                ////Номер договора
                object wdrepl = WdReplace.wdReplaceAll;
                //object searchtxt = "GreetingLine";
                object searchtxt = "категория";
                object newtxt    = (object)this.cmbЛьготнаяКатегория.Text;
                //object frwd = true;
                object frwd = false;
                doc.Content.Find.Execute(ref searchtxt, ref missing, ref missing, ref missing, ref missing, ref missing, ref frwd, ref missing, ref missing, ref newtxt, ref wdrepl, ref missing, ref missing,
                                         ref missing, ref missing);

                //Вставить таблицу
                object bookNaziv = "таблица";
                Range  wrdRng    = doc.Bookmarks.get_Item(ref bookNaziv).Range;

                object behavior     = Microsoft.Office.Interop.Word.WdDefaultTableBehavior.wdWord8TableBehavior;
                object autobehavior = Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitWindow;


                Microsoft.Office.Interop.Word.Table table = doc.Tables.Add(wrdRng, 1, 6, ref behavior, ref autobehavior);
                table.Range.ParagraphFormat.SpaceAfter = 6;
                table.Columns[1].Width = 40;
                table.Columns[2].Width = 140;
                table.Columns[3].Width = 80;
                table.Columns[4].Width = 110;//ширина столбца с номером акта
                table.Columns[5].Width = 70;
                table.Columns[6].Width = 80;
                table.Borders.Enable   = 1; // Рамка - сплошная линия
                table.Range.Font.Name  = "Times New Roman";
                //table.Range.Font.Size = 10;
                table.Range.Font.Size = 8;
                //счётчик строк
                int i = 1;

                //запишем данные в таблицу
                foreach (еестр item in list)
                {
                    table.Cell(i, 1).Range.Text = item.НомерПорядковый;

                    table.Cell(i, 2).Range.Text = item.ФИО;

                    table.Cell(i, 3).Range.Text = item.НомерДатаДоговора;
                    table.Cell(i, 4).Range.Text = item.НомерДатаАкта;
                    table.Cell(i, 5).Range.Text = item.СерияДатаВыдачиДокумента;
                    // table.Cell(i, 6).Range.Text = item.SNILS;
                    table.Cell(i, 6).Range.Text = item.СтоимсотьУслуги;

                    //doc.Words.Count.ToString();
                    Object beforeRow1 = Type.Missing;
                    table.Rows.Add(ref beforeRow1);

                    i++;
                }
                table.Rows[i].Delete();

                //выведим ФИО главврача
                string    глВрач     = "select ФИО_ГлавВрач from ГлавВрач where id_главВрач in (select id_главВрач from Поликлинника)";
                DataTable dtГлавВрач = ТаблицаБД.GetTable(глВрач, sCon, "Поликлинника");
                string    главВрач   = dtГлавВрач.Rows[0][0].ToString();

                //выведим ФИО глав буха
                string    глБух     = "select ФИО_ГлавБух from ГлавБух where id_главБух in (select id_главБух from Поликлинника)";
                DataTable dtГлавБух = ТаблицаБД.GetTable(глБух, sCon, "Поликлинника");
                string    главБух   = dtГлавБух.Rows[0][0].ToString();

                ////Номер договора
                object wdrepl2 = WdReplace.wdReplaceAll;
                //object searchtxt = "GreetingLine";
                object searchtxt2 = "главврач";
                object newtxt2    = (object)главВрач;
                //object frwd = true;
                object frwd2 = false;
                doc.Content.Find.Execute(ref searchtxt2, ref missing, ref missing, ref missing, ref missing, ref missing, ref frwd2, ref missing, ref missing, ref newtxt2, ref wdrepl2, ref missing, ref missing,
                                         ref missing, ref missing);


                ////Номер договора
                object wdrepl3 = WdReplace.wdReplaceAll;
                //object searchtxt = "GreetingLine";
                object searchtxt3 = "главбух";
                object newtxt3    = (object)главБух;
                //object frwd = true;
                object frwd3 = false;
                doc.Content.Find.Execute(ref searchtxt3, ref missing, ref missing, ref missing, ref missing, ref missing, ref frwd3, ref missing, ref missing, ref newtxt3, ref wdrepl3, ref missing, ref missing,
                                         ref missing, ref missing);

                //Должность на подписи
                string queryДолжность = "select Должность from ГлавВрач where id_главВрач = (select id_главВрач from Поликлинника)";
                string Predsedatel    = ТаблицаБД.GetTable(queryДолжность, ConnectionDB.ConnectionString(), "ФиоШев").Rows[0][0].ToString();

                object wdrepl4 = WdReplace.wdReplaceAll;//39
                //object searchtxt = "GreetingLine";
                object searchtxt4 = "Predsedatel";
                object newtxt4    = (object)Predsedatel;
                //object frwd = true;
                object frwd4 = false;
                doc.Content.Find.Execute(ref searchtxt4, ref missing, ref missing, ref missing, ref missing, ref missing, ref frwd4, ref missing, ref missing, ref newtxt4, ref wdrepl4, ref missing, ref missing,
                                         ref missing, ref missing);

                //должность руководителя ТО
                string    quyeryTO   = "select Должность, ФИО_Руководитель from ФиоШев where id_шев in (select id_шев from Комитет)";
                DataTable tabРуковод = ТаблицаБД.GetTable(quyeryTO, ConnectionDB.ConnectionString(), "Руководитель");

                //получим должность
                string должность = tabРуковод.Rows[0]["Должность"].ToString();

                object wdrepl5 = WdReplace.wdReplaceAll;//39
                //object searchtxt = "GreetingLine";
                object searchtxt5 = "должность";
                object newtxt5    = (object)должность;
                //object frwd = true;
                object frwd5 = false;
                doc.Content.Find.Execute(ref searchtxt5, ref missing, ref missing, ref missing, ref missing, ref missing, ref frwd5, ref missing, ref missing, ref newtxt5, ref wdrepl5, ref missing, ref missing,
                                         ref missing, ref missing);

                //получим ФИО руководителя ТО
                string руководитель = tabРуковод.Rows[0]["ФИО_Руководитель"].ToString();

                object wdrepl6 = WdReplace.wdReplaceAll;//39
                //object searchtxt = "GreetingLine";
                object searchtxt6 = "руководитель";
                object newtxt6    = (object)руководитель;
                //object frwd = true;
                object frwd6 = false;
                doc.Content.Find.Execute(ref searchtxt6, ref missing, ref missing, ref missing, ref missing, ref missing, ref frwd6, ref missing, ref missing, ref newtxt6, ref wdrepl6, ref missing, ref missing,
                                         ref missing, ref missing);

                app.Visible = true;

                //закроем окно
                this.Close();

                //Выгрузить реестр
                //UnloadDate unloadDate = new UnloadDate(strДата, endДата, this.cmbЛьготнаяКатегория.Text);

                if (this.еестрЗаключенныхДоговоров == true)
                {
                    UnloadDate    unloadDate = new UnloadDate(strДата, endДата, льготнаяКатегорияТекст);
                    List <Unload> unload     = unloadDate.Выгрузка();

                    //закроем окно
                    this.Close();

                    //Проверим в файле конфигурации Config.dll разрешена выгрузка реестра в файл или нет
                    using (FileStream fs = File.OpenRead("Config.dll"))
                        using (TextReader read = new StreamReader(fs))
                        {
                            string sConfig = read.ReadLine();
                            if (sConfig == "1")
                            {
                                //Разрешаем выгрузку реестра в файл
                                flagUnLoad = true;
                            }
                            else
                            {
                                //запрещаем выгрузку реестра в файл
                                flagUnLoad = false;
                            }
                        }

                    if (flagUnLoad == true)
                    {
                        //Проверим если список List<Unload> не пустой
                        if (unload.Count != 0)
                        {
                            //получим путь к файлу
                            //SaveFileDialog saveFile = new SaveFileDialg();
                            SaveFileDialog saveFile = new SaveFileDialog();
                            saveFile.DefaultExt = string.Empty;
                            saveFile.Filter     = "All files (*.*)|*.*";

                            //Получим красивое название файла
                            //string arDateStart = strДата.Replace('#', '_');
                            ////string arrDateStart = arDateStart.Replace('/', '_');

                            //string arrDateStart = arDateStart.Replace('/', '.');
                            ////string fileNameBg = arrDateStart;

                            //string arEndДата = "_" + this.dtEnd.Value.ToShortDateString();// .Replace('#', '_');
                            ////string arrEndДата = arEndДата.Replace('/', '_');

                            //string arrEndДата = arEndДата.Replace('/', '.');
                            ////string fileNameEnd = arrEndДата;

                            string arrDateStart = Convert.ToDateTime(this.dtStart.Value).ToShortDateString();
                            string arrEndДата   = Convert.ToDateTime(this.dtEnd.Value).ToShortDateString();

                            saveFile.FileName = arrDateStart + "_" + льготнаяКатегорияТекст + "_" + arrEndДата + ".r";
                            //saveFile.ShowDialog();

                            string fileBinaryName = string.Empty;


                            if (saveFile.ShowDialog() == DialogResult.OK)
                            {
                                fileBinaryName = saveFile.FileName;
                                //saveFile.InitialDirectory = @".\";
                                //WorkingDirectory
                            }
                            else
                            {
                                return;
                            }

                            //сериализуем список
                            FileStream      fs = new FileStream(fileBinaryName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                            BinaryFormatter bf = new BinaryFormatter();

                            //сериализация
                            bf.Serialize(fs, unload);

                            //Освободим в потоке все ресурсы
                            fs.Dispose();
                            fs.Close();

                            //Установим для проги текущую директорию для корректного считывания пути к БД
                            Environment.CurrentDirectory = System.Windows.Forms.Application.StartupPath;
                        }
                    }
                }

                //Конец
            }


            if (this.еестрЗаключенныхДоговоров == true)
            {
                //сформируем word
                string fName = "Реестр " + this.dtStart.Value.ToShortDateString().Replace('.', '_') + " " + this.dtEnd.Value.ToShortDateString().Replace('.', '_');

                //Выведим данные в отдельное окошко
                FormListReestr listR = new FormListReestr();

                //передадим в форму данные полученные от SQL Server
                listR.еестрАктов = list;

                //Передадим начало и конец отчётного периода
                listR.dtStart = this.dtStart.Value;
                listR.dtEnd   = this.dtEnd.Value;

                //передадим льготную категорию
                listR.ЛьготнаяКатегория = this.cmbЛьготнаяКатегория.Text.Trim();

                //передадим флаг о разрешении выгрузки реестров заключённых договоров
                listR.еестрЗаключенныхДоговоров = this.еестрЗаключенныхДоговоров;

                //Отобразим форму выбора актов выполненных работ
                listR.Show();

                //Закроем форму
                this.Close();
            }

            //распечатаем word
            //FileInfo fnDel = new FileInfo(System.Windows.Forms.Application.StartupPath + @"\Документы\Акт4.dot");
            // FileInfo fnDel = new FileInfo(System.Windows.Forms.Application.StartupPath + @"\Документы\"+fileName+".doc");
            //fnDel.Delete();
            //try
            //{
            //    //Скопируем шаблон в папку Документы
            //    FileInfo fn = new FileInfo(System.Windows.Forms.Application.StartupPath + @"\Шаблон\Реестр.doc");
            //    fn.CopyTo(System.Windows.Forms.Application.StartupPath + @"\Документы\" + fName + ".doc", true);
            //}
            //catch
            //{
            //    MessageBox.Show("Документ с таки именем уже существует");
            //}

            //string filName = System.Windows.Forms.Application.StartupPath + @"\Документы\" + fName + ".doc";

            ////Создаём новый Word.Application
            //Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

            ////Загружаем документ
            //Microsoft.Office.Interop.Word.Document doc = null;

            //object fileName = filName;
            //object falseValue = false;
            //object trueValue = true;
            //object missing = Type.Missing;

            //doc = app.Documents.Open(ref fileName, ref missing, ref trueValue,
            //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);

            ////зададим левый отступ
            //doc.PageSetup.LeftMargin = 40f;


            //////Номер договора
            //object wdrepl = WdReplace.wdReplaceAll;
            ////object searchtxt = "GreetingLine";
            //object searchtxt = "категория";
            //object newtxt = (object)this.cmbЛьготнаяКатегория.Text;
            ////object frwd = true;
            //object frwd = false;
            //doc.Content.Find.Execute(ref searchtxt, ref missing, ref missing, ref missing, ref missing, ref missing, ref frwd, ref missing, ref missing, ref newtxt, ref wdrepl, ref missing, ref missing,
            //ref missing, ref missing);

            ////Вставить таблицу
            //object bookNaziv = "таблица";
            //Range wrdRng = doc.Bookmarks.get_Item(ref  bookNaziv).Range;

            //object behavior = Microsoft.Office.Interop.Word.WdDefaultTableBehavior.wdWord8TableBehavior;
            //object autobehavior = Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitWindow;


            //Microsoft.Office.Interop.Word.Table table = doc.Tables.Add(wrdRng, 1, 6, ref behavior, ref autobehavior);
            //table.Range.ParagraphFormat.SpaceAfter = 6;
            //table.Columns[1].Width = 40;
            //table.Columns[2].Width = 140;
            //table.Columns[3].Width = 80;
            //table.Columns[4].Width = 110;//ширина столбца с номером акта
            //table.Columns[5].Width = 70;
            //table.Columns[6].Width = 80;
            //table.Borders.Enable = 1; // Рамка - сплошная линия
            //table.Range.Font.Name = "Times New Roman";
            ////table.Range.Font.Size = 10;
            //table.Range.Font.Size = 8;
            ////счётчик строк
            //int i = 1;

            ////запишем данные в таблицу
            //foreach (Реестр item in list)
            //{
            //    table.Cell(i, 1).Range.Text = item.НомерПорядковый;

            //    table.Cell(i, 2).Range.Text = item.ФИО;

            //    table.Cell(i, 3).Range.Text = item.НомерДатаДоговора;
            //    table.Cell(i, 4).Range.Text = item.НомерДатаАкта;
            //    table.Cell(i, 5).Range.Text = item.СерияДатаВыдачиДокумента;
            //    table.Cell(i, 6).Range.Text = item.СтоимсотьУслуги;

            //    //doc.Words.Count.ToString();
            //    Object beforeRow1 = Type.Missing;
            //    table.Rows.Add(ref beforeRow1);

            //    i++;
            //}
            //table.Rows[i].Delete();

            ////выведим ФИО главврача
            //string глВрач = "select ФИО_ГлавВрач from ГлавВрач where id_главВрач in (select id_главВрач from Поликлинника)";
            //DataTable dtГлавВрач = ТаблицаБД.GetTable(глВрач, sCon, "Поликлинника");
            //string главВрач = dtГлавВрач.Rows[0][0].ToString();

            ////выведим ФИО глав буха
            //string глБух = "select ФИО_ГлавБух from ГлавБух where id_главБух in (select id_главБух from Поликлинника)";
            //DataTable dtГлавБух = ТаблицаБД.GetTable(глБух, sCon, "Поликлинника");
            //string главБух = dtГлавБух.Rows[0][0].ToString();

            //////Номер договора
            //object wdrepl2 = WdReplace.wdReplaceAll;
            ////object searchtxt = "GreetingLine";
            //object searchtxt2 = "главврач";
            //object newtxt2 = (object)главВрач;
            ////object frwd = true;
            //object frwd2 = false;
            //doc.Content.Find.Execute(ref searchtxt2, ref missing, ref missing, ref missing, ref missing, ref missing, ref frwd2, ref missing, ref missing, ref newtxt2, ref wdrepl2, ref missing, ref missing,
            //ref missing, ref missing);


            //////Номер договора
            //object wdrepl3 = WdReplace.wdReplaceAll;
            ////object searchtxt = "GreetingLine";
            //object searchtxt3 = "главбух";
            //object newtxt3 = (object)главБух;
            ////object frwd = true;
            //object frwd3 = false;
            //doc.Content.Find.Execute(ref searchtxt3, ref missing, ref missing, ref missing, ref missing, ref missing, ref frwd3, ref missing, ref missing, ref newtxt3, ref wdrepl3, ref missing, ref missing,
            //ref missing, ref missing);

            ////Должность на подписи
            //string queryДолжность = "select Должность from ГлавВрач where id_главВрач = (select id_главВрач from Поликлинника)";
            //string Predsedatel = ТаблицаБД.GetTable(queryДолжность, ConnectionDB.ConnectionString(), "ФиоШев").Rows[0][0].ToString();

            //object wdrepl4 = WdReplace.wdReplaceAll;//39
            ////object searchtxt = "GreetingLine";
            //object searchtxt4 = "Predsedatel";
            //object newtxt4 = (object)Predsedatel;
            ////object frwd = true;
            //object frwd4 = false;
            //doc.Content.Find.Execute(ref searchtxt4, ref missing, ref missing, ref missing, ref missing, ref missing, ref frwd4, ref missing, ref missing, ref newtxt4, ref wdrepl4, ref missing, ref missing,
            //ref missing, ref missing);

            ////должность руководителя ТО
            //string quyeryTO = "select Должность, ФИО_Руководитель from ФиоШев where id_шев in (select id_шев from Комитет)";
            //DataTable tabРуковод = ТаблицаБД.GetTable(quyeryTO, ConnectionDB.ConnectionString(), "Руководитель");

            ////получим должность
            //string должность = tabРуковод.Rows[0]["Должность"].ToString();

            //object wdrepl5 = WdReplace.wdReplaceAll;//39
            ////object searchtxt = "GreetingLine";
            //object searchtxt5 = "должность";
            //object newtxt5 = (object)должность;
            ////object frwd = true;
            //object frwd5 = false;
            //doc.Content.Find.Execute(ref searchtxt5, ref missing, ref missing, ref missing, ref missing, ref missing, ref frwd5, ref missing, ref missing, ref newtxt5, ref wdrepl5, ref missing, ref missing,
            //ref missing, ref missing);

            ////получим ФИО руководителя ТО
            //string руководитель = tabРуковод.Rows[0]["ФИО_Руководитель"].ToString();

            //object wdrepl6 = WdReplace.wdReplaceAll;//39
            ////object searchtxt = "GreetingLine";
            //object searchtxt6 = "руководитель";
            //object newtxt6 = (object)руководитель;
            ////object frwd = true;
            //object frwd6 = false;
            //doc.Content.Find.Execute(ref searchtxt6, ref missing, ref missing, ref missing, ref missing, ref missing, ref frwd6, ref missing, ref missing, ref newtxt6, ref wdrepl6, ref missing, ref missing,
            //ref missing, ref missing);

            //app.Visible = true;

            ////закроем окно
            //this.Close();

            ////Выгрузить реестр
            ////UnloadDate unloadDate = new UnloadDate(strДата, endДата, this.cmbЛьготнаяКатегория.Text);

            //if(this.РеестрЗаключенныхДоговоров == true)
            //{
            //UnloadDate unloadDate = new UnloadDate(strДата, endДата, льготнаяКатегорияТекст);
            //List<Unload> unload = unloadDate.Выгрузка();

            ////закроем окно
            //this.Close();

            ////Проверим в файле конфигурации Config.dll разрешена выгрузка реестра в файл или нет
            //using (FileStream fs = File.OpenRead("Config.dll"))
            //using (TextReader read = new StreamReader(fs))
            //{
            //    string sConfig = read.ReadLine();
            //    if (sConfig == "1")
            //    {
            //        //Разрешаем выгрузку реестра в файл
            //        flagUnLoad = true;
            //    }
            //    else
            //    {
            //        //запрещаем выгрузку реестра в файл
            //        flagUnLoad = false;
            //    }
            //}

            //if (flagUnLoad == true)
            //{

            //    //Проверим если список List<Unload> не пустой
            //    if (unload.Count != 0)
            //    {

            //        //получим путь к файлу
            //        //SaveFileDialog saveFile = new SaveFileDialg();
            //        SaveFileDialog saveFile = new SaveFileDialog();
            //        saveFile.DefaultExt = string.Empty;
            //        saveFile.Filter = "All files (*.*)|*.*";

            //        //Получим красивое название файла
            //        //string arDateStart = strДата.Replace('#', '_');
            //        ////string arrDateStart = arDateStart.Replace('/', '_');

            //        //string arrDateStart = arDateStart.Replace('/', '.');
            //        ////string fileNameBg = arrDateStart;

            //        //string arEndДата = "_" + this.dtEnd.Value.ToShortDateString();// .Replace('#', '_');
            //        ////string arrEndДата = arEndДата.Replace('/', '_');

            //        //string arrEndДата = arEndДата.Replace('/', '.');
            //        ////string fileNameEnd = arrEndДата;

            //        string arrDateStart = Convert.ToDateTime(this.dtStart.Value).ToShortDateString();
            //        string arrEndДата = Convert.ToDateTime(this.dtEnd.Value).ToShortDateString();

            //        saveFile.FileName =  arrDateStart + "_" + льготнаяКатегорияТекст + "_" + arrEndДата + ".r";
            //        //saveFile.ShowDialog();

            //        string fileBinaryName = string.Empty;


            //        if (saveFile.ShowDialog() == DialogResult.OK)
            //        {
            //            fileBinaryName = saveFile.FileName;
            //            //saveFile.InitialDirectory = @".\";
            //            //WorkingDirectory
            //        }
            //        else
            //        {
            //            return;
            //        }

            //        //сериализуем список
            //        FileStream fs = new FileStream(fileBinaryName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            //        BinaryFormatter bf = new BinaryFormatter();

            //        //сериализация
            //        bf.Serialize(fs, unload);

            //        //Освободим в потоке все ресурсы
            //        fs.Dispose();
            //        fs.Close();

            //        //Установим для проги текущую директорию для корректного считывания пути к БД
            //        Environment.CurrentDirectory = System.Windows.Forms.Application.StartupPath;
            //    }
            //}


            //}
        }
예제 #20
0
파일: Foremen.cs 프로젝트: Ilyuac/DBProject
 protected void DoAct()
 {
     #region
     StreamReader  reader = new StreamReader(@"G:\Sql\SQL\sql\Library\Path.txt");
     string        text = reader.ReadToEnd(), path = null, Save = "";
     List <string> Text = new List <string>();
     Text.AddRange(text.Split('\n'));
     for (int i = 0; i < Text.Count; i++)
     {
         if (Text[i].Split('=')[0] == "PathAct")
         {
             path = Text[i].Split('=')[1];
         }
         if (Text[i].Split('=')[0] == "SaveAct")
         {
             Save = Text[i].Split('=')[1];
         }
     }
     reader.Close();
     #endregion
     Word.Application app     = new Word.Application();
     Word.Document    docWord = app.Documents.Open(@"G:\Sql\SQL\sql\Library\template\TempAct.docx", Visible: true, ReadOnly: false);
     app.Visible = false;
     Word.Bookmarks bookmark = docWord.Bookmarks;
     Word.Range     range;
     Word.Bookmark  mark = bookmark[1];
     range      = mark.Range;
     range.Text = BoxNomAct.Text;//номер
     connection = transaction.Connection();
     SqlCommand commandNameClient = new SqlCommand("SELECT Клиент.ФИО_Клиента FROM Клиент, Информация_о_Заявке, Оборудование_Клиента WHERE Клиент.[№_Клиента]=Оборудование_Клиента.[№_Клиента] and Оборудование_Клиента.SN_Оборудования=Информация_о_Заявке.SN_Оборудования and Информация_о_Заявке.НомерЗаявки=@nomberOrder", connection);
     commandNameClient.Parameters.AddWithValue("nomberOrder", BoxNomAct.Text);
     SqlDataReader readerNameClient = commandNameClient.ExecuteReader();
     readerNameClient.Read();
     mark       = bookmark[2];
     range      = mark.Range;
     range.Text = readerNameClient[0].ToString();//заказчик
     readerNameClient.Close();
     mark       = bookmark[3];
     range      = mark.Range;
     range.Text = "ООО Энерготех";//исполнитель
     mark       = bookmark[4];
     range      = mark.Range;
     Word.Table table = docWord.Tables.Add(range, checkedListDO.CheckedItems.Count + 2, 3);
     table.Borders.Enable = 1;
     table.Rows[1].Cells[1].Range.Text = "№";
     table.Rows[1].Cells[2].Range.Text = "Название";
     table.Rows[1].Cells[3].Range.Text = "Цена";
     SqlCommand commandCreateRow = new SqlCommand("INSERT INTO [Список_работ] ([Код_Работ], [НомерЗаявки]) VALUES (@Code, @Nomber)", connection);
     int        Sum = 0;
     for (int i = 0; i < checkedListDO.CheckedItems.Count; i++)
     {
         SqlCommand commandListWork = new SqlCommand("SELECT * FROM Прайс_лист WHERE Код_Работ=@CodeWork", connection);
         commandListWork.Parameters.AddWithValue("CodeWork", Convert.ToInt32(checkedListDO.CheckedItems[i].ToString().Split(' ')[0]));
         commandCreateRow.Parameters.AddWithValue("Nomber", BoxNomAct.Text);
         commandCreateRow.Parameters.AddWithValue("Code", Convert.ToInt32(checkedListDO.CheckedItems[i].ToString().Split(' ')[0]));
         SqlDataReader readerListWork = commandListWork.ExecuteReader();
         readerListWork.Read();
         table.Rows[i + 2].Cells[1].Range.Text = Convert.ToString(i + 1);      //№
         table.Rows[i + 2].Cells[2].Range.Text = readerListWork[1].ToString(); //Название
         table.Rows[i + 2].Cells[3].Range.Text = readerListWork[3].ToString(); //Цена
         Sum += Convert.ToInt32(readerListWork[3]);
         readerListWork.Close();
         commandCreateRow.ExecuteNonQuery();
         commandCreateRow.Parameters.Clear();
     }
     table.Rows[checkedListDO.CheckedItems.Count + 2].Cells[2].Range.Text = "Итого:";
     table.Rows[checkedListDO.CheckedItems.Count + 2].Cells[3].Range.Text = Convert.ToString(Sum);
     string link = String.Concat(@"G:\Sql\SQL\sql\Library\Act\", "A", BoxNomAct.Text, ".docx");
     docWord.SaveAs2(link);
     docWord.Close();
     app.Quit();
     SqlCommand commandAddLink = new SqlCommand("UPDATE Заказ SET [Акт_выполненых_работ]=@linkAct WHERE НомерЗаявки=@nomber", connection);
     commandAddLink.Parameters.AddWithValue("nomber", Convert.ToInt32(BoxNomAct.Text));
     commandAddLink.Parameters.AddWithValue("linkAct", link);
     commandAddLink.ExecuteNonQuery();
     MessageBox.Show("Акт выполненых работ по заказу №" + BoxNomAct.Text + " был успешно сформирован и сохранен.", "Соодщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
     checkedListDO.Items.Clear();
     LoadCheckListDO();
     UpdateActNom();
 }
예제 #21
0
        /// <summary>
        /// 添加静力触探摩阻力统计表格
        /// </summary>
        /// <param name="_cptStatistic">静力触探摩阻力统计数据</param>
        /// <returns></returns>
        public MSWord.Table AddPsStatisticTable(List <StatisticCPT> _cptStatistic)
        {
            // 填写表格标题
            Doc.Paragraphs.Last.Range.Text                = "表3 静力触探摩阻力统计表";
            Doc.Paragraphs.Last.Range.Font.Bold           = 1;
            Doc.Paragraphs.Last.Range.Font.Size           = 12;
            App.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            object unite = MSWord.WdUnits.wdStory;

            App.Selection.EndKey(ref unite, ref Nothing);

            // 定义表格对象
            MSWord.Table table = Tables.Add(App.Selection.Range, _cptStatistic.Count + 1, 10, ref Nothing, ref Nothing);

            // 填充行标题
            string[] rowheader = new string[] { "层号", "岩土名称", "统计数", "最大值", "最小值", "平均值", "标准差", "变异系数", "统计修正系数", "标准值" };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Cell(1, i).Range.Text = rowheader[i - 1];
            }

            // 设置文档格式
            Doc.PageSetup.LeftMargin  = 50F;
            Doc.PageSetup.RightMargin = 50F;

            // 设置表格格式
            table.Select();
            App.Selection.Tables[1].Rows.Alignment = WdRowAlignment.wdAlignRowCenter;
            table.Rows[1].Range.Bold = 1;
            for (int i = 2; i <= table.Rows.Count; i++)
            {
                table.Rows[i].Range.Bold              = 0;
                table.Columns[6].Cells[i].Range.Bold  = 1;
                table.Columns[10].Cells[i].Range.Bold = 1;
            }
            table.Range.Font.Size = 10.5F;
            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            table.Borders.OutsideLineStyle        = MSWord.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle         = MSWord.WdLineStyle.wdLineStyleSingle;
            float[] columnWidth = new float[] { 35, 80, 45, 45, 45, 45, 45, 35, 45, 45 };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Columns[i].Width = columnWidth[i - 1];
            }

            // 填充摩阻力数据
            for (int i = 2; i <= table.Rows.Count; i++)
            {
                table.Cell(i, 1).Range.Text  = _cptStatistic[i - 2].Layer;
                table.Cell(i, 2).Range.Text  = _cptStatistic[i - 2].Name;
                table.Cell(i, 3).Range.Text  = _cptStatistic[i - 2].Count.ToString("0");
                table.Cell(i, 4).Range.Text  = _cptStatistic[i - 2].Max.ToString("0.00");
                table.Cell(i, 5).Range.Text  = _cptStatistic[i - 2].Min.ToString("0.00");
                table.Cell(i, 6).Range.Text  = _cptStatistic[i - 2].Average.ToString("0.00");
                table.Cell(i, 7).Range.Text  = _cptStatistic[i - 2].StandardDeviation.ToString() == "-0.19880205" ? "/" : _cptStatistic[i - 2].StandardDeviation.ToString("0.00");
                table.Cell(i, 8).Range.Text  = _cptStatistic[i - 2].VariableCoefficient.ToString() == "-0.19880205" ? "/" : _cptStatistic[i - 2].VariableCoefficient.ToString("0.00");
                table.Cell(i, 9).Range.Text  = _cptStatistic[i - 2].CorrectionCoefficient.ToString() == "-0.19880205" ? "/" : _cptStatistic[i - 2].CorrectionCoefficient.ToString("0.00");
                table.Cell(i, 10).Range.Text = _cptStatistic[i - 2].StandardValue.ToString() == "-0.19880205" ? "/" : _cptStatistic[i - 2].StandardValue.ToString("0.00");
            }

            //返回
            return(table);
        }
예제 #22
0
        private static bool CreateTableInfo(Microsoft.Office.Interop.Word.Application WordApp, Microsoft.Office.Interop.Word.Document WordDoc, List <SQLTableInfo> lstdb)
        {
            if (lstdb != null)
            {
                //移动焦点并换行
                object count  = lstdb.Count + 10;
                object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;   //换一行;
                WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing); //移动焦点
                WordApp.Selection.TypeParagraph();                              //插入段落

                //文档中创建表格
                Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, lstdb.Count + 4, 11, ref Nothing, ref Nothing);
                //设置表格样式
                newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
                newTable.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                //newTable.Columns[1].Width = 100f;
                //newTable.Columns[2].Width = 220f;
                //newTable.Columns[3].Width = 105f;


                //填充表格内容
                newTable.Cell(1, 1).Range.Text = string.Format("表{0}", tablenamenow);
                newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体
                //合并单元格
                newTable.Cell(1, 1).Merge(newTable.Cell(1, 11));
                WordApp.Selection.Cells.VerticalAlignment   = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //垂直居中
                WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;       //水平居中

                //填充表格内容
                newTable.Cell(2, 1).Range.Text       = string.Format("共有{0}个字段", lstdb.Count);
                newTable.Cell(2, 1).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
                //合并单元格
                newTable.Cell(2, 1).Merge(newTable.Cell(2, 11));
                newTable.AllowAutoFit = true;

                WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                newTable.Cell(3, 1).Range.Text            = "字段名";
                newTable.Cell(3, 2).Range.Text            = "类型";
                newTable.Cell(3, 3).Range.Text            = "标识";
                newTable.Cell(3, 4).Range.Text            = "主键";
                newTable.Cell(3, 5).Range.Text            = "字段长度";
                newTable.Cell(3, 6).Range.Text            = "字段描述";
                newTable.Cell(3, 7).Range.Text            = "保留位";
                newTable.Cell(3, 8).Range.Text            = "默认值";
                newTable.Cell(3, 9).Range.Text            = "允许为空";
                newTable.Cell(3, 10).Range.Text           = "字节长度";
                newTable.Cell(3, 11).Range.Text           = "自动计算";

                string t_tabledesc_ = null;
                int    row          = 3;
                foreach (var fied in lstdb)
                {
                    if (t_tabledesc_ == null)
                    {
                        t_tabledesc_ = (string )fied.t_tabledesc;
                    }
                    row += 1;
                    newTable.Cell(row, 1).Range.Text  = fied.t_fieldname;
                    newTable.Cell(row, 2).Range.Text  = fied.t_fieldtype;
                    newTable.Cell(row, 3).Range.Text  = fied.t_identity;
                    newTable.Cell(row, 4).Range.Text  = fied.t_tablekey;
                    newTable.Cell(row, 5).Range.Text  = fied.t_fieldlenght.ToString();
                    newTable.Cell(row, 6).Range.Text  = (string)fied.t_fielddesc;
                    newTable.Cell(row, 7).Range.Text  = fied.t_fieldscale.ToString();
                    newTable.Cell(row, 8).Range.Text  = fied.t_fielddefaultvalue;
                    newTable.Cell(row, 9).Range.Text  = fied.t_fieldcannull;
                    newTable.Cell(row, 10).Range.Text = fied.t_fieldbitcount.ToString();
                    newTable.Cell(row, 11).Range.Text = fied.t_fieldiscomputed;
                }

                Common.ShowInfo(string.Format("恭喜!表{0}的文档生成完毕!", tablenamenow));

                newTable.Cell(lstdb.Count + 4, 1).Range.Text = "说明:" + t_tabledesc_;
                newTable.Cell(lstdb.Count + 4, 1).Merge(newTable.Cell(lstdb.Count + 4, 11));
                //移动焦点并换行
                count  = lstdb.Count + 10;
                WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;          //换一行;
                WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing); //移动焦点
                WordApp.Selection.TypeParagraph();                              //插入段落
            }
            return(true);
        }
예제 #23
0
        /// <summary>
        /// 添加颗粒分析试验统计表格
        /// </summary>
        /// <param name="_gatStatistic">颗粒分析试验数据</param>
        /// <returns></returns>
        public MSWord.Table AddGATStatisticTable(List <StatisticGAT> _gatStatistic)
        {
            // 填写表格标题
            Doc.Paragraphs.Last.Range.Text                = "表5 颗粒分析试验成果统计表";
            Doc.Paragraphs.Last.Range.Font.Bold           = 1;
            Doc.Paragraphs.Last.Range.Font.Size           = 12;
            App.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            object unite = MSWord.WdUnits.wdStory;

            App.Selection.EndKey(ref unite, ref Nothing);

            // 定义表格对象
            MSWord.Table table = Tables.Add(App.Selection.Range, _gatStatistic.Count + 2, 7, ref Nothing, ref Nothing);

            // 填充列标题
            table.Cell(1, 1).Range.Text = "分层编号及名称";
            table.Cell(1, 2).Range.Text = "粒组分布百分含量(%)";
            string[] rowheader = new string[]
            {
                ">20mm",
                "20~2mm",
                "2~0.5mm",
                "0.5~0.25mm",
                "0.25~0.075mm",
                "<0.075mm"
            };
            for (int i = 1; i < table.Columns.Count; i++)
            {
                table.Cell(2, i + 1).Range.Text = rowheader[i - 1];
            }

            // 设置文档格式
            Doc.PageSetup.LeftMargin  = 50F;
            Doc.PageSetup.RightMargin = 50F;

            // 设置表格格式
            table.Select();
            App.Selection.Tables[1].Rows.Alignment = WdRowAlignment.wdAlignRowCenter;

            foreach (Row row in table.Rows)
            {
                row.Range.Bold = 0;
            }
            table.Rows[1].Range.Bold = 1;
            table.Rows[2].Range.Bold = 1;

            table.Range.Font.Size = 10.0F;

            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

            table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle  = MSWord.WdLineStyle.wdLineStyleSingle;

            float[] columnWidth = new float[] { 100, 50, 60, 60, 80, 80, 70 };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Columns[i].Width = columnWidth[i - 1];
            }

            // 填充试验数据
            for (int i = 0; i < _gatStatistic.Count; i++)
            {
                table.Cell(i + 3, 1).Range.Text = _gatStatistic[i].Layer + _gatStatistic[i].Name;
                table.Cell(i + 3, 2).Range.Text = _gatStatistic[i].Group100To20.ToString() == "-0.19880205" ? "/" : _gatStatistic[i].Group100To20.ToString("0.0");
                table.Cell(i + 3, 3).Range.Text = _gatStatistic[i].Group20To2.ToString() == "-0.19880205" ? "/" : _gatStatistic[i].Group20To2.ToString("0.0");
                table.Cell(i + 3, 4).Range.Text = _gatStatistic[i].Group2To0_5.ToString() == "-0.19880205" ? "/" : _gatStatistic[i].Group2To0_5.ToString("0.0");
                table.Cell(i + 3, 5).Range.Text = _gatStatistic[i].Group0_5To0_25.ToString() == "-0.19880205" ? "/" : _gatStatistic[i].Group0_5To0_25.ToString("0.0");
                table.Cell(i + 3, 6).Range.Text = _gatStatistic[i].Group0_25To0_075.ToString() == "-0.19880205" ? "/" : _gatStatistic[i].Group0_25To0_075.ToString("0.0");
                table.Cell(i + 3, 7).Range.Text = _gatStatistic[i].Group0_075To0.ToString() == "-0.19880205" ? "/" : _gatStatistic[i].Group0_075To0.ToString("0.0");
            }

            // 合并层号及名称单元格
            table.Cell(1, 1).Merge(table.Cell(2, 1));
            table.Cell(1, 2).Merge(table.Cell(1, 7));

            // 返回
            return(table);
        }
예제 #24
0
        /// <summary>
        /// 写飞行时序
        /// </summary>
        /// <param name="TableName">表头</param>
        /// <param name="Table">特征表</param>
        /// <param name="TName">总时间列名称</param>
        /// <param name="TjName">级时间列名称</param>
        /// <param name="NoteName">注释列名称</param>
        public void WriteFlightSquence2Document(string TableName, DataTable Table, string TName, string TjName, string NoteName)
        {
            try
            {
                if (Table == null)
                {
                    throw new Exception("DataTable为Null!");
                }
                if (Table.Rows.Count < 1)
                {
                    throw new Exception("DataTable中无数据!");
                }

                //水平居中
                oWord.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                //写表头
                oWord.Selection.TypeText(TableName);

                //  创建表格
                WORD.Table newTable = oDoc.Tables.Add(oWord.Selection.Range, Table.Rows.Count + 1, 3);

                //表格加边框
                newTable.Borders.Enable = 1;
                //newTable.Borders.OutsideLineStyle = WORD.WdLineStyle.wdLineStyleThickThinLargeGap;

                newTable.Cell(1, 1).Range.Text = "飞行时序";
                newTable.Cell(1, 2).Range.Text = "t(s)";
                newTable.Cell(1, 3).Range.Text = "t*(s)";

                //写数据
                double tlast    = 1e10;
                int    TableRow = 1;
                foreach (DataRow dr in Table.Rows)
                {
                    //  此行数据的时刻
                    double tt = (double)dr[TName];

                    //  若与上段时间不同,则认为新数据,写入列数位置增加,否则下次覆盖
                    if (Math.Abs(tt - tlast) > 1e-5)
                    {
                        TableRow++;
                    }
                    tlast = tt;

                    //  将输入DataTable中的行部分数据写入Word文档的表格列中
                    for (int i = 0; i < Table.Rows.Count; i++)
                    {
                        //  写入第一列名称
                        newTable.Cell(TableRow, 1).Range.Text = (string)dr[NoteName];

                        //  写入第二列总时间
                        StringBuilder line = new StringBuilder(100);
                        line.AppendFormat("{0,12:F3}", (double)dr[TName]);
                        newTable.Cell(TableRow, 2).Range.Text = line.ToString();

                        //  写入第三列分时间
                        StringBuilder line2 = new StringBuilder(100);
                        line2.AppendFormat("{0,12:F3}", (double)dr[TjName]);
                        newTable.Cell(TableRow, 3).Range.Text = line2.ToString();
                    }
                }

                //  删除剩余的行
                for (int i = TableRow + 1; i < Table.Rows.Count + 2; i++)
                {
                    newTable.Rows[TableRow + 1].Select();
                    oWord.Selection.Cells.Delete();
                }

                //自动适应文字宽度
                newTable.Select();
                oWord.Selection.Cells.AutoFit();

                //  将光标移至表格下方
                newTable.Rows[TableRow].Select();
                oWord.Selection.GoToNext(WORD.WdGoToItem.wdGoToLine);
                oWord.Selection.InsertBreak();
                oWord.Selection.GoToNext(WORD.WdGoToItem.wdGoToPage);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + "\n" + "将DataTable写入Word文档出错!");
            }
        }
예제 #25
0
        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            int n, m;

            try
            {
                n = int.Parse(textBox1.Text);
                m = int.Parse(textBox2.Text);
            }
            catch
            {
                MessageBox.Show("错误!");
                return;
            }
            if (n < 2 || m < 1)
            {
                MessageBox.Show("错误!");
                return;
            }
            sFD.Filter           = "DOCX 文档 (*.docx) |*.docx";
            sFD.FilterIndex      = 1;
            sFD.RestoreDirectory = true;
            object path;

            if (sFD.ShowDialog() == DialogResult.OK)
            {
                path = sFD.FileName.ToString();
            }
            else
            {
                return;
            }
            MSWord.Application wordApp = new MSWord.ApplicationClass();
            Object             Nothing = Missing.Value;

            MSWord.Document wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //wordApp.Visible = true;
            object unite = MSWord.WdUnits.wdStory;

            wordDoc.PageSetup.PaperSize    = MSWord.WdPaperSize.wdPaperA4;          //设置纸张样式为A4纸
            wordDoc.PageSetup.Orientation  = MSWord.WdOrientation.wdOrientPortrait; //排列方式为垂直方向
            wordDoc.PageSetup.TopMargin    = 57.0f;
            wordDoc.PageSetup.BottomMargin = 57.0f;
            wordDoc.PageSetup.LeftMargin   = 57.0f;
            wordDoc.PageSetup.RightMargin  = 57.0f;
            #region 添加表格、填充数据、设置表格行列宽高、合并单元格、添加表头斜线、给单元格添加图片
            //wordDoc.Content.InsertAfter("\n");//这一句与下一句的顺序不能颠倒,原因还没搞透
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
            //object WdLine2 = MSWord.WdUnits.wdLine;//换一行;
            //wordApp.Selection.MoveDown(ref WdLine2, 6, ref Nothing);//向下跨15行输入表格,这样表格就在文字下方了,不过这是非主流的方法

            wordDoc.Paragraphs.Last.Range.Font.Name = "Proxy 3";
            wordDoc.Paragraphs.Last.Range.Font.Bold = 1;
            //设置表格的行数和列数
            int tableRow    = 20;
            int tableColumn = 5 * 2 + 1;

            for (int cas = 0; cas < m; ++cas)
            {
                if (cas > 0)
                {
                    wordApp.Selection.EndKey(ref unite, ref Nothing); wordDoc.Content.InsertAfter("\n");
                }
                wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾
                //定义一个Word中的表格对象
                MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, tableRow, tableColumn, ref Nothing, ref Nothing);

                //默认创建的表格没有边框,这里修改其属性,使得创建的表格带有边框
                //表格的索引是从1开始的。
                //wordDoc.Tables[1].Cell(1, 1).Range.Text = "列\n行";
                //设置table样式
                table.Borders.Enable  = 1;                                         //这个值可以设置得很大,例如5、13等等
                table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast; //高度规则是:行高有最低值下限?
                table.Rows.Height     = wordApp.CentimetersToPoints(0.8F);         //

                table.Range.Font.Name = "Proxy 3";
                table.Range.Font.Size = 20F;
                table.Range.Font.Bold = 1;

                table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;       //表格文本居中
                table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //文本垂直贴到底部
                //设置table边框样式
                //table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;//表格外框是双线
                //table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;//表格内框是单线
                table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;
                table.Borders.InsideLineStyle  = MSWord.WdLineStyle.wdLineStyleNone;

                //table.Rows[1].Range.Font.Bold = 1;//加粗
                //table.Rows[1].Range.Font.Size = 12F;
                //table.Cell(1, 1).Range.Font.Size = 10.5F;
                wordApp.Selection.Cells.Height = 35;//所有单元格的高度

                Random rnd = new Random();
                for (int i = 1; i <= tableRow; i++)
                {
                    for (int j = 1, a, b, c; j <= 2; j++)
                    {
                        do
                        {
                            a = rnd.Next(0, n);
                            b = rnd.Next(0, n);
                        } while (a + b > n);
                        c = rnd.Next(1, 8);
                        switch (c)
                        {
                        case 1:
                            table.Cell(i, j * 6 - 5).Range.Text = a.ToString();
                            table.Cell(i, j * 6 - 4).Range.Text = "+";
                            table.Cell(i, j * 6 - 3).Range.Text = b.ToString();
                            table.Cell(i, j * 6 - 2).Range.Text = "=";
                            table.Cell(i, j * 6 - 1).Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
                            break;

                        case 2:
                            table.Cell(i, j * 6 - 5).Range.Text = a.ToString();
                            table.Cell(i, j * 6 - 4).Range.Text = "+";
                            table.Cell(i, j * 6 - 3).Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
                            table.Cell(i, j * 6 - 2).Range.Text = "=";
                            table.Cell(i, j * 6 - 1).Range.Text = (a + b).ToString();
                            break;

                        case 3:
                            table.Cell(i, j * 6 - 5).Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
                            table.Cell(i, j * 6 - 4).Range.Text = "+";
                            table.Cell(i, j * 6 - 3).Range.Text = b.ToString();
                            table.Cell(i, j * 6 - 2).Range.Text = "=";
                            table.Cell(i, j * 6 - 1).Range.Text = (a + b).ToString();
                            break;

                        case 4:
                            table.Cell(i, j * 6 - 5).Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
                            table.Cell(i, j * 6 - 4).Range.Text = "-";
                            table.Cell(i, j * 6 - 3).Range.Text = a.ToString();
                            table.Cell(i, j * 6 - 2).Range.Text = "=";
                            table.Cell(i, j * 6 - 1).Range.Text = b.ToString();
                            break;

                        case 5:
                            table.Cell(i, j * 6 - 5).Range.Text = (a + b).ToString();
                            table.Cell(i, j * 6 - 4).Range.Text = "-";
                            table.Cell(i, j * 6 - 3).Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
                            table.Cell(i, j * 6 - 2).Range.Text = "=";
                            table.Cell(i, j * 6 - 1).Range.Text = b.ToString();
                            break;

                        case 6:
                            table.Cell(i, j * 6 - 5).Range.Text = (a + b).ToString();
                            table.Cell(i, j * 6 - 4).Range.Text = "-";
                            table.Cell(i, j * 6 - 3).Range.Text = b.ToString();
                            table.Cell(i, j * 6 - 2).Range.Text = "=";
                            table.Cell(i, j * 6 - 1).Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
                            break;

                        case 7:
                            c = rnd.Next(0, 2);
                            table.Cell(i, j * 6 - 5).Range.Text = (c > 0 ? a + b : a).ToString();
                            table.Cell(i, j * 6 - 4).Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
                            table.Cell(i, j * 6 - 3).Range.Text = b.ToString();
                            table.Cell(i, j * 6 - 2).Range.Text = "=";
                            table.Cell(i, j * 6 - 1).Range.Text = (c == 0 ? a + b : a).ToString();
                            break;
                        }
                    }
                    progressBar1.Value = (100 * (cas * tableRow + i) + (tableRow * m - 1) / 2) / (tableRow * m);
                }
            }

/*
 *          //添加行
 *          table.Rows.Add(ref Nothing);
 *          table.Rows[tableRow + 1].Height = 35;//设置新增加的这行表格的高度
 *          //向新添加的行的单元格中添加图片
 *          string FileName = Environment.CurrentDirectory + "\\6.jpg";//图片所在路径
 *          object LinkToFile = false;
 *          object SaveWithDocument = true;
 *          object Anchor = table.Cell(tableRow + 1, tableColumn).Range;//选中要添加图片的单元格
 *          wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
 *
 *          wordDoc.Application.ActiveDocument.InlineShapes[1].Width = 50;//图片宽度
 *          wordDoc.Application.ActiveDocument.InlineShapes[1].Height = 35;//图片高度
 *
 *          // 将图片设置为四周环绕型
 *          MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
 *          s.WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare;
 */

            //除第一行外,其他行的行高都设置为20
            //for (int i = 2; i <= tableRow; i++)
            //{
            //    table.Rows[i].Height = 20;
            //}

            //将表格左上角的单元格里的文字(“行” 和 “列”)居右
            //table.Cell(1, 1).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;
            //将表格左上角的单元格里面下面的“列”字移到左边,相比上一行就是将ParagraphFormat改成了Paragraphs[2].Format
            //table.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;

            //table.Columns[1].Width = 50;//将第 1列宽度设置为50

            //将其他列的宽度都设置为75
            // for (int i = 2; i <= tableColumn; i++)
            //{
            //    table.Columns[i].Width = 75;
            //}


            //添加表头斜线,并设置表头的样式
            //table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Visible = true;
            //table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Color = MSWord.WdColor.wdColorRed;
            //table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].LineWidth = MSWord.WdLineWidth.wdLineWidth150pt;

            //合并单元格
            //table.Cell(4, 4).Merge(table.Cell(4, 5));//横向合并

            //table.Cell(2, 3).Merge(table.Cell(4, 3));//纵向合并,合并(2,3),(3,3),(4,3)

            #endregion
            //WdSaveFormat为Word 2003文档的保存格式
            object format = MSWord.WdSaveFormat.wdFormatDocumentDefault;// office 2007就是wdFormatDocumentDefault
            //将wordDoc文档对象的内容保存为DOCX文档
            MessageBox.Show("完成");
            wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //关闭wordDoc文档对象
            //看是不是要打印
            //wordDoc.PrintOut();
            wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
            //关闭wordApp组件对象
            wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
        }
예제 #26
0
        //#####################################################################
        /// <summary>
        ///  将DataTable中部分数据写入到Word文档表格中(若有时间相同点,则由后点覆盖前点)
        /// </summary>
        /// <param name="TableName">表头名称</param>
        /// <param name="Table"></param>
        /// <param name="TName">时间列名称、判断重复时间点</param>
        /// <param name="NoteName">注释列名称</param>
        /// <param name="Name">选择写入文档的列名称</param>
        /// <param name="Label">列说明</param>
        /// <param name="Symbol">符号</param>
        /// <param name="Unit">单位</param>
        /// <param name="Quotiety">系数</param>
        /// <param name="Precision">数据精度、小数点位数</param>
        public void WriteTable2Document(string TableName, DataTable Table, string TName, string NoteName, string[] Name, string[] Label, string[] Symbol, string[] Unit, string[] Quotiety, string[] Precision)
        {
            try
            {
                if (Table == null)
                {
                    throw new Exception("DataTable为Null!");
                }
                if (Table.Rows.Count < 1)
                {
                    throw new Exception("DataTable中无数据!名称:" + Table.TableName);
                }
                if (Name.Length < 1)
                {
                    throw new Exception("输入数组为0");
                }

                //水平居中
                oWord.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                //写表头
                oWord.Selection.TypeText(TableName);

                //  创建表格
                WORD.Table newTable = oDoc.Tables.Add(oWord.Selection.Range, Name.Length + 1, Table.Rows.Count + 3);

                //表格加边框
                newTable.Borders.Enable = 1;
                //newTable.Borders.OutsideLineStyle = WORD.WdLineStyle.wdLineStyleThickThinLargeGap;

                newTable.Cell(1, 1).Range.Text = "名称";
                newTable.Cell(1, 2).Range.Text = "符号";
                newTable.Cell(1, 3).Range.Text = "单位";

                //向表格前三列中写入:说明,符号,单位
                for (int i = 0; i < Name.Length; i++)
                {
                    newTable.Cell(i + 2, 1).Range.Text = Label[i];
                    newTable.Cell(i + 2, 2).Range.Text = Symbol[i];
                    newTable.Cell(i + 2, 3).Range.Text = Unit[i];
                }

                //写数据
                double tlast    = 1e10;
                int    TableCol = 3;
                foreach (DataRow dr in Table.Rows)
                {
                    //  此行数据的时刻
                    double tt = (double)dr[TName];

                    //  若与上段时间不同,则认为新数据,写入列数位置增加,否则下次覆盖
                    if (Math.Abs(tt - tlast) > 1e-5)
                    {
                        TableCol++;
                    }
                    tlast = tt;

                    //  将输入DataTable中的行部分数据写入Word文档的表格列中
                    for (int i = 0; i < Name.Length; i++)
                    {
                        //  写入第一行段名称
                        newTable.Cell(1, TableCol).Range.Text = (string)dr[NoteName];

                        //  写入各行数据
                        StringBuilder line = new StringBuilder(100);
                        line.AppendFormat("{0,12:F" + Precision[i] + "}", (double)dr[Name[i]] * Convert.ToDouble(Quotiety[i]));
                        newTable.Cell(i + 2, TableCol).Range.Text = line.ToString();
                    }
                }

                //  删除剩余的列
                for (int i = TableCol + 1; i < Table.Rows.Count + 4; i++)
                {
                    newTable.Columns[TableCol + 1].Select();
                    oWord.Selection.Cells.Delete();
                }

                //自动适应文字宽度
                newTable.Select();
                oWord.Selection.Cells.AutoFit();

                //  将光标移至表格下方
                newTable.Rows[Name.Length + 1].Select();
                oWord.Selection.GoToNext(WORD.WdGoToItem.wdGoToLine);
                oWord.Selection.InsertBreak();
                oWord.Selection.GoToNext(WORD.WdGoToItem.wdGoToPage);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + "\n" + "将DataTable写入Word文档出错!");
            }
        }
예제 #27
0
        public string GetWordFileDataMethod(string fileName, out string output1, out string output2,
                                            out string output3, out string output4, out string output5,
                                            out string output6, out string output7, out string output8,
                                            out string output9, out string output10, out string output11,
                                            out string output12, out string output13, out string output14,
                                            out string output15, out string output16)
        {
            Microsoft.Office.Interop.Word.Application app  = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Documents   docs = app.Documents;
            Microsoft.Office.Interop.Word.Document    doc  = docs.Open(fileName, ReadOnly: true);

            Microsoft.Office.Interop.Word.Table t1     = doc.Tables[1];
            Microsoft.Office.Interop.Word.Range r1     = t1.Range;
            Microsoft.Office.Interop.Word.Cells cells1 = r1.Cells;

            Microsoft.Office.Interop.Word.Table t2     = doc.Tables[2];
            Microsoft.Office.Interop.Word.Range r2     = t2.Range;
            Microsoft.Office.Interop.Word.Cells cells2 = r2.Cells;



            //convert tables to text to get rid of bullet points at the end of text fields
            Regex rg = new Regex("^[A-Za-z0-9/$ !|\\[]{}%&()]$");//regex filter on output text accepting characters alphanumeric and /


            Regex rgg = new Regex("^[A-Za-z0-9/$ .!|\\[]{}%&()]$");//regex filter on output text accepting characters alphanumeric and /

            //if (!rg.IsMatch(cells1[2].Range.Text))
            //{
            //    string employerName = "";
            //}
            //else
            //{
            //    string employerName = rg.Replace(cells1[2].Range.Text, "");
            //}

            //Table 1


            string employerName         = rg.Replace(cells1[2].Range.Text, "");
            string employerID           = rg.Replace(cells1[4].Range.Text, "");
            string region               = rg.Replace(cells1[6].Range.Text, "");
            string segment              = rg.Replace(cells1[8].Range.Text, "");
            string benefitEffectiveDate = rg.Replace(cells1[10].Range.Text, "");
            string currentProducts      = rg.Replace(cells1[12].Range.Text, "");
            string addedProducts        = rg.Replace(cells1[14].Range.Text, "");
            string newImpFlag           = rg.Replace(cells1[16].Range.Text, "");
            string IM_AM       = rg.Replace(cells1[18].Range.Text, "");
            string impDeadline = rg.Replace(cells1[20].Range.Text, "");
            string sftpCreds   = "";

            //Remove MS Word table1 character '•' from the ends of all the text fields

            employerName         = employerName.Remove(employerName.Length - 1, 1);
            employerID           = employerID.Remove(employerID.Length - 1, 1);
            region               = region.Remove(region.Length - 1, 1);
            segment              = segment.Remove(segment.Length - 1, 1);
            benefitEffectiveDate = benefitEffectiveDate.Remove(benefitEffectiveDate.Length - 1, 1);
            currentProducts      = currentProducts.Remove(currentProducts.Length - 1, 1);
            addedProducts        = addedProducts.Remove(addedProducts.Length - 1, 1);
            newImpFlag           = newImpFlag.Remove(newImpFlag.Length - 1, 1);
            IM_AM       = IM_AM.Remove(IM_AM.Length - 1, 1);
            impDeadline = impDeadline.Remove(impDeadline.Length - 1, 1);

            //get rid of carraige return in all fields

            employerName         = employerName.TrimEnd('\r', '\n');
            employerID           = employerID.TrimEnd('\r', '\n');
            region               = region.TrimEnd('\r', '\n');
            segment              = segment.TrimEnd('\r', '\n');
            benefitEffectiveDate = benefitEffectiveDate.TrimEnd('\r', '\n');
            currentProducts      = currentProducts.TrimEnd('\r', '\n');
            addedProducts        = addedProducts.TrimEnd('\r', '\n');
            newImpFlag           = newImpFlag.TrimEnd('\r', '\n');
            IM_AM       = IM_AM.TrimEnd('\r', '\n');
            impDeadline = impDeadline.TrimEnd('\r', '\n');
            sftpCreds   = sftpCreds.TrimEnd('\r', '\n');



            //added field to the implementation table
            if (t1.Rows.Count == 11)
            {
                sftpCreds = rg.Replace(cells1[22].Range.Text, "");
            }
            else if (t1.Rows.Count == 10)
            {
                sftpCreds = string.Empty;
            }



            output1  = employerName;
            output2  = employerID;
            output3  = region;
            output4  = segment;
            output5  = benefitEffectiveDate;
            output6  = currentProducts;
            output7  = addedProducts;
            output8  = newImpFlag;
            output9  = IM_AM;
            output10 = impDeadline;
            output11 = sftpCreds;



            //Table 2


            string contactName        = rgg.Replace(cells2[6].Range.Text, "");
            string contactphoneNumber = rgg.Replace(cells2[7].Range.Text, "");
            string contactEmail       = rgg.Replace(cells2[8].Range.Text, "");
            string contactType        = rgg.Replace(cells2[9].Range.Text, "");
            string fileType           = rgg.Replace(cells2[10].Range.Text, "");

            //Remove MS Word table2 character '•' from the ends of all the text fields

            contactName        = contactName.Remove(contactName.Length - 1, 1);
            contactphoneNumber = contactphoneNumber.Remove(contactphoneNumber.Length - 1, 1);
            contactEmail       = contactEmail.Remove(contactEmail.Length - 1, 1);
            contactType        = contactType.Remove(contactType.Length - 1, 1);
            fileType           = fileType.Remove(fileType.Length - 1, 1);


            //assign output variables
            output12 = contactName;
            output13 = contactphoneNumber;
            output14 = contactEmail;
            output15 = contactType;
            output16 = fileType;



            GetterSetterString getData = new GetterSetterString();

            getData.DataValue = employerName;


            //docs.Close();
            app.Quit();


            return(""); //This is the output door for the outputs to go through
        }
예제 #28
0
        private void Save(object sender, RoutedEventArgs e)
        {
            SaveButton.IsEnabled = false;
            gamerounds.Add(Gameround.getTotal());
            Application application = new Application();
            Document    doc         = application.Documents.Add();
            Range       range       = doc.Range();

            range.Text = "ПРОТОКОЛ МАТЕМАТИЧЕСКОГО БОЯ\n";
            range.Bold = 1;
            range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            range      = doc.Range(range.End - 1);
            range.Bold = 0;
            range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
            if (!(string.IsNullOrWhiteSpace(first_players) && string.IsNullOrWhiteSpace(secound_players)))
            {
                string[] fcommand = first_players.Split('\n');
                string[] scommand = secound_players.Split('\n');
                Table    commands = range.Tables.Add(range, Math.Max(fcommand.Length, scommand.Length) + 1, 2);
                commands.Cell(1, 1).Range.Text = fn;
                commands.Cell(1, 1).Range.Bold = 1;
                commands.Cell(1, 2).Range.Text = sn;
                commands.Cell(1, 2).Range.Bold = 1;
                for (int i = 1; i <= Math.Max(fcommand.Length, scommand.Length); i++)
                {
                    if (i <= fcommand.Length && !string.IsNullOrWhiteSpace(fcommand[i - 1]))
                    {
                        commands.Cell(i + 1, 1).Range.Text = (i).ToString() + ". " + fcommand[i - 1].Replace("\r", "");
                    }
                    if (i <= scommand.Length && !string.IsNullOrWhiteSpace(scommand[i - 1]))
                    {
                        commands.Cell(i + 1, 2).Range.Text = (i).ToString() + ". " + scommand[i - 1].Replace("\r", "");
                    }
                }
            }
            range      = doc.Range(range.End - 1);
            range.Text = "В конкурсе капитанов победил капитан команды ";
            if (leader)
            {
                range.Text = "В конкурсе капитанов победил капитан команды " + fn;
            }
            else
            {
                range.Text = "В конкурсе капитанов победил капитан команды " + sn;
            }
            range = doc.Range(range.End - 1);
            Table table = doc.Tables.Add(range, gamerounds.Count + 1, 5);

            table.Borders.Enable           = 1;
            table.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth100pt;
            table.Borders.InsideLineWidth  = WdLineWidth.wdLineWidth025pt;
            foreach (Row row in table.Rows)
            {
                foreach (Cell cell in row.Cells)
                {
                    if (cell.RowIndex == 1)
                    {
                        if (cell.ColumnIndex == 1)
                        {
                            cell.Range.Text = "Раунд";
                            cell.Range.Bold = 1;
                        }
                        if (cell.ColumnIndex == 2)
                        {
                            cell.Range.Text = fn;
                            cell.Range.Bold = 1;
                        }
                        if (cell.ColumnIndex == 3)
                        {
                            cell.Range.Text = "Вызов";
                            cell.Range.Bold = 1;
                        }
                        if (cell.ColumnIndex == 4)
                        {
                            cell.Range.Text = sn;
                            cell.Range.Bold = 1;
                        }
                        if (cell.ColumnIndex == 5)
                        {
                            cell.Range.Text = "Жюри";
                            cell.Range.Bold = 1;
                        }
                    }
                    else
                    {
                        Gameround gr = gamerounds[cell.RowIndex - 2];
                        if (cell.ColumnIndex == 1)
                        {
                            cell.Range.Text = gr.id;
                        }
                        if (cell.ColumnIndex == 2)
                        {
                            cell.Range.Text = gr.first.ToString();
                        }
                        if (cell.ColumnIndex == 3)
                        {
                            cell.Range.Text = gr.vyzov;
                        }
                        if (cell.ColumnIndex == 4)
                        {
                            cell.Range.Text = gr.secound.ToString();
                        }
                        if (cell.ColumnIndex == 5)
                        {
                            cell.Range.Text = gr.zhury.ToString();
                        }
                    }
                }
            }
            gamerounds.RemoveAt(gamerounds.Count - 1);
            range      = doc.Range(range.End - 1);
            range.Text = "\n" + DateTime.Today.ToShortDateString();
            range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
            doc.Save();
            doc.Close();
            application.Quit();
            SaveButton.IsEnabled = true;
        }
예제 #29
0
파일: WordWork.cs 프로젝트: RenatGaliew/-
        public string ListStart(Person person)
        {
            FileName = $"{Environment.CurrentDirectory}\\{Pathes.DirectoryGenerateList}\\{person.FileNameDOCX()}";
            InitializeShablon(Pathes.ListShablon, FileName);

            Word.Table wordtable = worddocument.Tables[2];

            var    wordcellrange = wordtable.Cell(2, 3).Range;
            string fio           = person.LongString();

            fio += Environment.NewLine;
            fio += person.Telefon;
            wordcellrange.Text = fio;
            string row3 = person.Birthday.ToLongDateString();

            row3              += Environment.NewLine + person.BirthdayMesto;
            wordcellrange      = wordtable.Cell(3, 3).Range;
            wordcellrange.Text = row3;
            wordcellrange      = wordtable.Cell(4, 3).Range;
            wordcellrange.Text = person.Country;

            wordcellrange      = wordtable.Cell(5, 3).Range;
            wordcellrange.Text = person.VK;

            wordcellrange      = wordtable.Cell(6, 3).Range;
            wordcellrange.Text = person.Health;

            wordcellrange      = wordtable.Cell(7, 3).Range;
            wordcellrange.Text = person.VUZ;

            wordcellrange      = wordtable.Cell(8, 3).Range;
            wordcellrange.Text = person.Specialnost;

            wordcellrange      = wordtable.Cell(9, 3).Range;
            wordcellrange.Text = person.Diplom;

            wordcellrange      = wordtable.Cell(10, 3).Range;
            wordcellrange.Text = person.VKR;

            wordcellrange      = wordtable.Cell(11, 3).Range;
            wordcellrange.Text = person.Statya;

            wordcellrange      = wordtable.Cell(12, 3).Range;
            wordcellrange.Text = person.SienceName;

            wordcellrange      = wordtable.Cell(13, 3).Range;
            wordcellrange.Text = person.Soiskatelstvo == 0 ? "Нет" : "Да" + ", " + person.Exams;

            wordcellrange      = wordtable.Cell(14, 3).Range;
            wordcellrange.Text = person.SportName;

            wordcellrange      = wordtable.Cell(15, 3).Range;
            wordcellrange.Text = person.Napravlenie;

            wordcellrange      = wordtable.Cell(16, 3).Range;
            wordcellrange.Text = person.Dopusk;

            wordcellrange      = wordtable.Cell(17, 3).Range;
            wordcellrange.Text = person.Info;

            return(SaveAndQuitPDF(person));
        }
예제 #30
0
        private void PrintPricelist()
        {
            var    wordApp    = new Word.Application();
            string reportPath = "";

            try
            {
                reportPath =
                    Application.StartupPath + @"\pricelist_" +
                    DateTime.Now.Year + "_" +
                    DateTime.Now.Month + "_" +
                    DateTime.Now.Day + "_" +
                    DateTime.Now.Hour + "_" +
                    DateTime.Now.Minute + "_" +
                    DateTime.Now.Second +
                    ".docx";
                File.Copy(_pathPriceList, reportPath);

                wordApp.Visible = false;
                var wordDoc = wordApp.Documents.Open(reportPath);

                ReplaceWordStub("{date}", DateTime.Now.Date.ToShortDateString(), wordDoc);

                Word.Table table = wordDoc.Tables[1];

                table.Rows[1].Cells[1].Range.Text = "Наименование";
                table.Rows[1].Cells[2].Range.Text = "Ед. измерения";
                table.Rows[1].Cells[3].Range.Text = "Цена";
                table.Rows[1].Cells[4].Range.Text = "Наличие";

                string        ConnectionString = ConfigurationManager.ConnectionStrings["supplyGood.Properties.Settings.MainDBConnectionString"].ConnectionString;
                SqlConnection sqlconn          = new SqlConnection(ConnectionString);
                try
                {
                    sqlconn.Open();
                    SqlCommand    command = new SqlCommand("SELECT g_name, g_unit, g_price, COALESCE(SUM(st_amount), 0) as Amount FROM Good FULL JOIN Stock ON Stock.id_good=Good.id GROUP BY g_name, g_unit, g_price ORDER BY Amount DESC, g_name DESC, g_unit DESC", sqlconn);
                    SqlDataReader reader  = command.ExecuteReader();
                    int           i       = 0;
                    while (reader.Read())
                    {
                        table.Rows.Add();
                        for (int j = 0; j < 3; j++)
                        {
                            table.Rows[i + 2].Cells[j + 1].Range.Text = reader[j].ToString();
                        }
                        table.Rows[i + 2].Cells[4].Range.Text = Convert.ToInt32(reader["Amount"]) > 0 ? "Есть в наличии" : "Нет в наличии";
                        i++;
                    }
                }
                catch (Exception ex) { }
                finally
                {
                    sqlconn.Close();
                }

                object missing = System.Reflection.Missing.Value;
                wordDoc.Save();
                wordApp.Visible = true;
            }
            catch (Exception e)
            {
                MessageBox.Show("Не удалось сформировать отчет" + Environment.NewLine + e.Message,
                                "Ошибка",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }
예제 #31
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;
     }
 }
예제 #32
0
        public static bool WordReplace(string filePath, Dictionary <string, string> datas)
        {
            bool result = false;

            Microsoft.Office.Interop.Word._Application app = null;
            Microsoft.Office.Interop.Word._Document    doc = null;

            object nullobj = Type.Missing;
            object file    = filePath;


            try
            {
                app = new Microsoft.Office.Interop.Word.Application();//new Microsoft.Office.Interop.Word.ApplicationClass();

                doc = app.Documents.Open(
                    ref file, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj, ref nullobj) as Microsoft.Office.Interop.Word._Document;
                object tmp          = "tt1";
                object missingValue = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Range startRange = app.ActiveDocument.Bookmarks.get_Item(ref tmp).Range;


                //删除指定书签位置后的第一个表格
                //Microsoft.Office.Interop.Word.Table tbl = startRange.Tables[1];
                //tbl.Delete();

                //添加表格
                for (int i = 0; i < 8; i++)
                {
                    MSWord.Table table = doc.Tables.Add(startRange, 3, 2, ref missingValue, ref missingValue);
                    table.AllowAutoFit               = true;
                    table.Borders.Enable             = 1;                                         //这个值可以设置得很大,例如5、13等等
                    table.Rows.HeightRule            = MSWord.WdRowHeightRule.wdRowHeightExactly; //高度规则是:行高有最低值下限?
                    table.Rows.Height                = 15;                                        //
                    table.Columns.PreferredWidthType = MSWord.WdPreferredWidthType.wdPreferredWidthPercent;

                    table.Columns[1].PreferredWidth = 30;
                    table.Columns[2].PreferredWidth = 70;

                    table.Range.Font.Size       = 10.5F;
                    table.Range.Font.Bold       = 0;
                    table.Cell(1, 1).Range.Text = "文件名";
                    table.Cell(2, 1).Range.Text = "SHA256校验码";
                    table.Cell(3, 1).Range.Text = "时间戳时间";
                    table.Cell(1, 2).Range.Text = "智臻链";
                    table.Cell(2, 2).Range.Text = "rerererererererererererererererererererererere\r\nerererererererererererererererererererererererer\r\nerererererererererererererererererererererererererere";
                    table.Cell(2, 2).HeightRule = MSWord.WdRowHeightRule.wdRowHeightAuto;
                    table.Cell(3, 2).Range.Text = "15393034920943048";
                }



                object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;


                foreach (var item in datas)
                {
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();
                    string oldStr = item.Key;                       //需要被替换的文本
                                        string newStr = item.Value; //替换文本 


                                        if (newStr == null)
                    {
                        newStr = "";
                    }
                    int newStrLength = newStr.Length;
                    if (newStrLength <= 255) // 长度未超过255时,直接替换
                    {
                                            {
                            app.Selection.Find.Text             = oldStr;
                            app.Selection.Find.Replacement.Text = newStr;


                            app.Selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj,
                                                       ref nullobj, ref nullobj, ref nullobj,
                                                       ref nullobj, ref nullobj, ref nullobj,
                                                       ref nullobj, ref objReplace, ref nullobj,
                                                       ref nullobj, ref nullobj, ref nullobj);
                            continue;
                        }
                    }


                                        //word文本替换长度不能超过255
                                        int hasSubLength = 0;
                    int itemLength = 255 - oldStr.Length;
                    while (true)
                    {
                        string itemStr   = "";
                        int    subLength = 0;
                        if (newStrLength - hasSubLength <= 255)
                        {
                                                                 // 剩余的内容不超过255,直接替换
                                                    {
                                app.Selection.Find.ClearFormatting();
                                app.Selection.Find.Replacement.ClearFormatting();


                                app.Selection.Find.Text             = oldStr;
                                app.Selection.Find.Replacement.Text = newStr.Substring(hasSubLength, newStrLength - hasSubLength);


                                app.Selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj,
                                                           ref nullobj, ref nullobj, ref nullobj,
                                                           ref nullobj, ref nullobj, ref nullobj,
                                                           ref nullobj, ref objReplace, ref nullobj,
                                                           ref nullobj, ref nullobj, ref nullobj);


                                break; // 结束循环
                                                       
                            }
                        }


                                                // 由于Word中换行为“^p”两个字符不能分割
                                                // 如果分割位置将换行符分开了,则本次少替换一个字符
                                                if (newStr.Substring(hasSubLength, itemLength).EndsWith("^") &&
                                                    newStr.Substring(hasSubLength, itemLength + 1).EndsWith("p"))
                        {
                            subLength = itemLength - 1;
                        }
                        else
                        {
                            subLength = itemLength;
                        }


                        itemStr = newStr.Substring(hasSubLength, subLength) + oldStr;


                        app.Selection.Find.ClearFormatting();
                        app.Selection.Find.Replacement.ClearFormatting();


                        app.Selection.Find.Text             = oldStr;
                        app.Selection.Find.Replacement.Text = itemStr;


                        app.Selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj,
                                                   ref nullobj, ref nullobj, ref nullobj,
                                                   ref nullobj, ref nullobj, ref nullobj,
                                                   ref nullobj, ref objReplace, ref nullobj,
                                                   ref nullobj, ref nullobj, ref nullobj);


                        hasSubLength += subLength;
                    }
                }

                //    object tmp = "tttttt";
                //object missingValue = System.Reflection.Missing.Value;

                //Microsoft.Office.Interop.Word.Range startRange = app.ActiveDocument.Bookmarks.get_Item(ref tmp).Range;


                ////删除指定书签位置后的第一个表格
                //Microsoft.Office.Interop.Word.Table tbl = startRange.Tables[1];
                //    tbl.Delete();

                ////添加表格
                //doc.Tables.Add(startRange, 5, 4, ref missingValue, ref missingValue);

                //    //为表格划线
                //    startRange.Tables[1].Borders[MSWord.WdBorderType.wdBorderTop].LineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
                //    startRange.Tables[1].Borders[MSWord.WdBorderType.wdBorderLeft].LineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
                //    startRange.Tables[1].Borders[MSWord.WdBorderType.wdBorderRight].LineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
                //    startRange.Tables[1].Borders[MSWord.WdBorderType.wdBorderBottom].LineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
                //    startRange.Tables[1].Borders[MSWord.WdBorderType.wdBorderHorizontal].LineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
                //    startRange.Tables[1].Borders[MSWord.WdBorderType.wdBorderVertical].LineStyle = MSWord.WdLineStyle.wdLineStyleSingle;


                //保存
                doc.Save();


                result = true;
            }
            catch (Exception e)
            {
                result = false;
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close(ref nullobj, ref nullobj, ref nullobj);
                    doc = null;
                }
                if (app != null)
                {
                    app.Quit(ref nullobj, ref nullobj, ref nullobj);
                    app = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return(result);
        }
예제 #33
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();
                    }
                });


            });
        }
예제 #34
0
        public void ExportDataTableToWord(System.Data.DataTable srcDgv, string filePath)
        {
            killWinWordProcess();
            if (srcDgv.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可供导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                if (filePath != null)
                {
                    object path = filePath;
                    Object none = System.Reflection.Missing.Value;
                    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                    Document document = wordApp.Documents.Open(ref path, ref miss, ref miss, ref miss
                                                               , ref miss, ref miss, ref miss, ref miss, ref miss
                                                               , ref miss, ref miss, ref miss, ref miss);
                    //搜索书签
                    Boolean find = false;
                    foreach (Microsoft.Office.Interop.Word.Bookmark bm in document.Bookmarks)
                    {
                        if (bm.Name == "data")
                        {
                            find = true;
                        }
                    }
                    if (!find)
                    {
                        MessageBox.Show("模板有误,请选择正确的模板");
                        return;
                    }

                    wordApp.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    object oStart = "data";
                    Microsoft.Office.Interop.Word.Range range = document.Bookmarks.get_Item(ref oStart).Range;

                    //建立表格
                    Microsoft.Office.Interop.Word.Table table = document.Tables.Add(range, srcDgv.Rows.Count + 1, srcDgv.Columns.Count, ref none, ref none);
                    try
                    {
                        for (int i = 0; i < srcDgv.Columns.Count; i++)//输出标题
                        {
                            table.Cell(1, i + 1).Range.InsertAfter(srcDgv.Columns[i].ColumnName);
                        }
                        //输出控件中的记录
                        for (int i = 0; i < srcDgv.Rows.Count; i++)
                        {
                            for (int j = 0; j < srcDgv.Columns.Count; j++)
                            {
                                table.Cell(i + 2, j + 1).Range.InsertAfter(srcDgv.Rows[i][j].ToString());
                            }
                        }
                        table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        table.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);

                        MessageBox.Show("数据已经成功导出到:" + filePath, "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        killWinWordProcess();
                    }
                    catch (System.Exception e)
                    {
                        MessageBox.Show(e.Message, "提示", MessageBoxButtons.OK);
                    }
                }
            }
        }
예제 #35
0
 private int check_Kernel(List<OfficeElement> ls)
 {
     int points = 0, i;
     int curPart = -1;            //当前正在分析哪一部分的考点
     for (i = 0; i < ls.Count; i++)
     {
         OfficeElement oe = ls[i];
         #region 具体考点对象定位
         if (oe.AttribName == "Root")
             continue;
         if (oe.AttribName == "Documents")
             continue;
         if (oe.AttribName == "Paragraph")
         {
             #region 段落定位
             try
             {
                 int paraIdx = int.Parse(oe.AttribValue);
                 stuPara = stuDoc.Paragraphs[paraIdx];
                 ansPara = ansDoc.Paragraphs[paraIdx];
             }
             catch
             {
                 points = 0;
                 break;
             }
             #endregion
             curPart = PART_PARAGRAPH;
             continue;
         }
         if (oe.AttribName == "Table")
         {
             #region 表格定位
             try
             {
                 int tabIdx = int.Parse(oe.AttribValue);
                 stuTab = stuDoc.Tables[tabIdx];
                 ansTab = ansDoc.Tables[tabIdx];
             }
             catch
             {
                 points = 0;
                 break;
             }
             #endregion
             curPart = PART_TABLE;
             continue;
         }
         if (oe.AttribName == "Cell")
         {
             #region 单元格定位
             try
             {
                 int rowIdx, colIdx, commaIdx;
                 commaIdx = oe.AttribValue.IndexOf(',');
                 rowIdx = int.Parse(oe.AttribValue.Substring(0, commaIdx));
                 colIdx = int.Parse(oe.AttribValue.Substring(commaIdx + 1));
                 stuCell = stuTab.Cell(rowIdx, colIdx);
                 ansCell = ansTab.Cell(rowIdx, colIdx);
             }
             catch
             {
                 points = 0;
                 break;
             }
             #endregion
             curPart = PART_CELL;
             continue;
         }
         if (oe.AttribName == "Textbox")
         {
             #region 文本框定位
             try
             {
                 int tbIdx = int.Parse(oe.AttribValue);
                 object ob = tbIdx;
                 stuSp = stuDoc.Shapes.get_Item(ref ob);
                 ansSp = ansDoc.Shapes.get_Item(ref ob);
                 stuTf = stuSp.TextFrame;
                 ansTf = ansSp.TextFrame;
             }
             catch
             {
                 points = 0;
                 break;
             }
             #endregion
             curPart = PART_TEXTBOX;
             continue;
         }
         if (oe.AttribName == "PageSetup")
         {
             #region 页面设置定位
             try
             {
                 stuPs = stuDoc.PageSetup;
                 ansPs = ansDoc.PageSetup;
             }
             catch
             {
                 points = 0;
                 break;
             }
             #endregion
             continue;
         }
         #endregion
         #region 段落属性判分
         if (curPart == PART_PARAGRAPH)
         {
             switch (oe.AttribName)
             {
                 case "Indent":
                     break;
                 case "Font":
                     stuRange = stuPara.Range;
                     ansRange = ansPara.Range;
                     break;
                 case "Dropcap":
                     stuDc = stuPara.DropCap;
                     ansDc = ansPara.DropCap;
                     break;
                 case "TextColumns":
                     stuTc = stuPara.Range.PageSetup.TextColumns;
                     ansTc = ansPara.Range.PageSetup.TextColumns;
                     break;
                 #region 段落部分
                 case "Alignment":
                     if (stuPara.Alignment == ansPara.Alignment)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "CharacterUnitFirstLineIndent":
                     if (stuPara.CharacterUnitFirstLineIndent == ansPara.CharacterUnitFirstLineIndent)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "CharacterUnitLeftIndent":
                     if (stuPara.CharacterUnitLeftIndent == ansPara.CharacterUnitLeftIndent)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "CharacterUnitRightIndent":
                     if (stuPara.CharacterUnitRightIndent == ansPara.CharacterUnitRightIndent)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "LineUnitBefore":
                     if (stuPara.LineUnitBefore == ansPara.LineUnitBefore)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "LineUnitAfter":
                     if (stuPara.LineUnitAfter == ansPara.LineUnitAfter)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "LineSpacingRule":
                     if (stuPara.LineSpacingRule == ansPara.LineSpacingRule)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "LineSpacing":
                     if (stuPara.LineSpacing == ansPara.LineSpacing)
                         points = int.Parse(oe.AttribValue);
                     break;
                 #endregion
                 #region 文字部分
                 case "Text":
                     if (stuRange.Text == ansRange.Text)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "FontSize":
                     if (stuRange.Font.Size == ansRange.Font.Size)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "FontName":
                     if (stuRange.Font.Name == ansRange.Font.Name)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Bold":
                     if (stuRange.Font.Bold == ansRange.Font.Bold)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Italic":
                     if (stuRange.Font.Italic == ansRange.Font.Italic)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Underline":
                     if (stuRange.Font.Underline == ansRange.Font.Underline)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "UnderlineColor":
                     if (stuRange.Font.UnderlineColor == ansRange.Font.UnderlineColor)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "ForeColor":
                     if (stuRange.Font.Color == ansRange.Font.Color)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "HighLightColor":
                     if (stuRange.HighlightColorIndex == ansRange.HighlightColorIndex)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Superscript":
                     if (stuRange.Font.Superscript == ansRange.Font.Superscript)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Subscript":
                     if (stuRange.Font.Subscript == ansRange.Font.Subscript)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Spacing":
                     if (stuRange.Font.Spacing == ansRange.Font.Spacing)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Animation":
                     if (stuRange.Font.Animation == ansRange.Font.Animation)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "BackgroundPatternColor":
                     if (stuRange.Shading.BackgroundPatternColor == ansRange.Shading.BackgroundPatternColor)
                         points = int.Parse(oe.AttribValue);
                     break;
                 #endregion
                 #region 首字下沉
                 case "Position":
                     if (stuDc.Position == ansDc.Position)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "DcFontName":
                     if (stuDc.FontName == ansDc.FontName)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "LinesToDrop":
                     if (stuDc.LinesToDrop == ansDc.LinesToDrop)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "DistanceFromText":
                     if (stuDc.DistanceFromText == ansDc.DistanceFromText)
                         points = int.Parse(oe.AttribValue);
                     break;
                 #endregion
                 #region 分栏与栏宽
                 case "TextColumnsCount":
                     if (stuTc.Count == ansTc.Count)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "TextColumnsWidth":
                     if (stuTc.Width == ansTc.Width)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "TextColumnsSpacing":
                     if (stuTc.Spacing == ansTc.Spacing)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "TextColumnsLineBetween":
                     if (stuTc.LineBetween == ansTc.LineBetween)
                         points = int.Parse(oe.AttribValue);
                     break;
                 #endregion
             }
             continue;
         }
         #endregion
         #region 表格属性判分
         if (curPart == PART_TABLE)
         {
             switch (oe.AttribName)
             {
                 case "Rows":
                     if (stuTab.Rows.Count == ansTab.Rows.Count)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Columns":
                     if (stuTab.Columns.Count == ansTab.Columns.Count)
                         points = int.Parse(oe.AttribValue);
                     break;
             }
             continue;
         }
         #endregion
         #region 单元格属性判分
         if (curPart == PART_CELL)
         {
             switch (oe.AttribName)
             {
                 case "Text":
                     if (stuCell.Range.Text == ansCell.Range.Text)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Height":
                     if (stuCell.Height == ansCell.Height)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Width":
                     if (stuCell.Width == ansCell.Width)
                         points = int.Parse(oe.AttribValue);
                     break;
             }
             continue;
         }
         #endregion
         #region 文本框属性判分
         if (curPart == PART_TEXTBOX)
         {
             switch (oe.AttribName)
             {
                 case "Text":
                     if (stuTf.TextRange.Text == ansTf.TextRange.Text)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Orientation":
                     if (stuTf.Orientation == ansTf.Orientation)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "FontName":
                     if (stuTf.TextRange.Font.Name == ansTf.TextRange.Font.Name)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "FontSize":
                     if (stuTf.TextRange.Font.Size == ansTf.TextRange.Font.Size)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "ForeColor":
                     if (stuTf.TextRange.Font.Color == ansTf.TextRange.Font.Color)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "HighLightColor":
                     if (stuTf.TextRange.HighlightColorIndex == ansTf.TextRange.HighlightColorIndex)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Spacing":
                     if (stuTf.TextRange.Font.Spacing == ansTf.TextRange.Font.Spacing)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Alignment":
                     if (stuTf.TextRange.ParagraphFormat.Alignment == ansTf.TextRange.ParagraphFormat.Alignment)
                         points = int.Parse(oe.AttribValue);
                     break;
             }
             continue;
         }
         #endregion
         #region 页面设置属性判分
         if (curPart == PART_PAGESETUP)
         {
             switch (oe.AttribName)
             {
                 case "TopMargin":
                     if (stuPs.TopMargin == ansPs.TopMargin)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "BottomMargin":
                     if (stuPs.BottomMargin == ansPs.BottomMargin)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "LeftMargin":
                     if (stuPs.LeftMargin == ansPs.LeftMargin)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "RightMargin":
                     if (stuPs.RightMargin == ansPs.RightMargin)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "HeaderDistance":
                     if (stuPs.HeaderDistance == ansPs.HeaderDistance)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "FooterDistance":
                     if (stuPs.FooterDistance == ansPs.FooterDistance)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "Orientation":
                     if (stuPs.Orientation == ansPs.Orientation)
                         points = int.Parse(oe.AttribValue);
                     break;
                 case "GutterPos":
                     if (stuPs.GutterPos == ansPs.GutterPos)
                         points = int.Parse(oe.AttribValue);
                     break;
             }
             continue;
         }
         #endregion
     }
     return points;
 }
예제 #36
0
        private bool ProcessClipboard()
        {
            Excel.Application xlApp   = new Excel.Application();
            Word.Application  WordApp = new Word.Application();

            if (xlApp == null)
            {
                MessageBox.Show("Excel is not properly installed!!", "Excel COM error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            if (WordApp == null)
            {
                MessageBox.Show("Word is not properly installed!!", "Word COM error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            object miss = System.Reflection.Missing.Value; //Common for Excel and Word

            b_PasteClipBoard.Text = "Processing Clipboard to Excel";

            xlApp.Visible = false;
            Excel.Workbook  xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            xlWorkBook  = xlApp.Workbooks.Add(miss);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            //Fix WorkSheet Font & Font Size
            xlApp.StandardFont     = "Arial";
            xlApp.StandardFontSize = 9.5;


            //Format all Cells are Text
            Excel.Range xlCells = xlWorkBook.Worksheets[1].Cells;
            xlCells.NumberFormat = "@";

            int rowID       = 1;
            int colID       = 1;
            int totalxlRows = 0;
            int totalxlCols = 0;

            //Copy Clipboard content to Excel Worksheet
            using (StringReader reader = new StringReader(Clipboard.GetText()))
            {
                string line = string.Empty;
                do
                {
                    line = reader.ReadLine();
                    if (line != null)
                    {
                        String[] fieldArr = line.Split('\t');
                        foreach (string field in fieldArr)
                        {
                            xlWorkSheet.Cells[rowID, colID] = field;
                            colID++;
                        }
                        if (rowID == 1)
                        {
                            totalxlCols = colID - 1;
                        }
                        rowID++;
                        colID = 1;
                    }
                } while ((line != null));
                totalxlRows = rowID - 1;
            }

            //Check that we have imported at least one full row
            if ((totalxlRows == 0) || (totalxlCols == 0))
            {
                MessageBox.Show("No data were copied to Excel", "Excel Processing Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            //Fix Data
            for (int currCol = 1; currCol <= totalxlCols; currCol++)
            {
                for (int currRow = 1; currRow <= totalxlRows; currRow++)
                {
                    //Fix Object Type
                    if (xlWorkSheet.Cells[1, currCol].Value.ToString() == "Type")
                    {
                        xlWorkSheet.Cells[currRow, currCol] = FormatType(xlWorkSheet.Cells[currRow, currCol].Value.ToString());
                    }

                    //Fix Date
                    if (xlWorkSheet.Cells[1, currCol].Value.ToString() == "Date")
                    {
                        xlWorkSheet.Cells[currRow, currCol] = FormatDate(xlWorkSheet.Cells[currRow, currCol].Value.ToString());
                    }
                }
            }


            //Finished importing data to Excel Proceed with Word
            b_PasteClipBoard.Text = "Processing Excel to Word";

            //Copy Data To Word
            this.Cursor = Cursors.Default;
            this.Cursor = Cursors.WaitCursor;

            bool showWord = !Properties.Settings.Default.UseClipboard;

            WordApp.Visible = showWord;
            object visible     = true;
            object SaveChanges = true;

            string templatePath     = Properties.Settings.Default.TemplatePath;
            string templateFileName = Path.GetFileNameWithoutExtension(Properties.Settings.Default.TemplateFileName);
            string TempDir          = @Path.GetDirectoryName(templatePath) + @"\";

            object workingPath = TempDir + templateFileName + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".docx";

            //Copy the template so we don't make any changes in it.
            File.Copy(templatePath.ToString(), workingPath.ToString(), true);

            tempFilesCreated.Add(workingPath.ToString());

            //Open Word Template
            Word.Document docs = WordApp.Documents.Open(ref workingPath, ref miss, ref miss,
                                                        ref miss, ref miss, ref miss, ref miss,
                                                        ref miss, ref miss, ref miss, ref visible,
                                                        ref miss, ref miss, ref miss, ref miss,
                                                        ref miss);

            //Get First Word Table
            Word.Table wordTable = docs.Tables[1];

            //Create Extra Lines to fit Excel Data
            for (int i = 2; i < totalxlRows; i++) //Template already has 1 line
            {
                wordTable.Rows.Add();
            }

            //Fill Table with Excel Data
            foreach (Word.Cell c in wordTable.Rows[1].Cells)                   //Loop through Word Table Columns
            {
                for (int currxlCol = 1; currxlCol <= totalxlCols; currxlCol++) //Loop through Excel Columns
                {
                    string xlString = xlWorkSheet.Cells[1, currxlCol].Value.ToString();
                    if (xlString.IndexOf(" ") > -1)
                    {
                        xlString = xlString.Substring(0, xlString.IndexOf(" "));
                    }
                    string wordString = c.Range.Text.ToString();
                    Console.WriteLine("Excel: " + xlString + " <=> Word: " + wordString);

                    //Populate Object Type
                    if (xlString == "Type" && wordString.IndexOf(xlString) > -1)
                    {
                        for (int currxlRow = 2; currxlRow <= totalxlRows; currxlRow++)
                        {
                            wordTable.Cell(currxlRow, currxlCol).Range.Text = xlWorkSheet.Cells[currxlRow, currxlCol].Value.ToString();
                        }
                    }
                    //Populate Object ID
                    if (xlString == "ID" && wordString.IndexOf(xlString) > -1)
                    {
                        for (int currxlRow = 2; currxlRow <= totalxlRows; currxlRow++)
                        {
                            wordTable.Cell(currxlRow, currxlCol).Range.Text = xlWorkSheet.Cells[currxlRow, currxlCol].Value.ToString();
                        }
                    }

                    //Populate Name
                    if (xlString == "Name" && wordString.IndexOf(xlString) > -1)
                    {
                        for (int currxlRow = 2; currxlRow <= totalxlRows; currxlRow++)
                        {
                            wordTable.Cell(currxlRow, currxlCol).Range.Text = xlWorkSheet.Cells[currxlRow, currxlCol].Value.ToString();
                        }
                    }

                    //Populate Modified
                    if (xlString == "Modified" && wordString.IndexOf(xlString) > -1)
                    {
                        for (int currxlRow = 2; currxlRow <= totalxlRows; currxlRow++)
                        {
                            wordTable.Cell(currxlRow, currxlCol).Range.Text = xlWorkSheet.Cells[currxlRow, currxlCol].Value.ToString();
                        }
                    }

                    //Populate Version
                    if (xlString == "Version" && wordString.IndexOf(xlString) > -1)
                    {
                        for (int currxlRow = 2; currxlRow <= totalxlRows; currxlRow++)
                        {
                            wordTable.Cell(currxlRow, currxlCol).Range.Text = xlWorkSheet.Cells[currxlRow, currxlCol].Value.ToString();
                        }
                    }

                    //Populate Date
                    if (xlString == "Date" && wordString.IndexOf(xlString) > -1)
                    {
                        for (int currxlRow = 2; currxlRow <= totalxlRows; currxlRow++)
                        {
                            wordTable.Cell(currxlRow, currxlCol).Range.Text = xlWorkSheet.Cells[currxlRow, currxlCol].Value.ToString();
                        }
                    }

                    //Populate Time
                    if (xlString == "Time" && wordString.IndexOf(xlString) > -1)
                    {
                        for (int currxlRow = 2; currxlRow <= totalxlRows; currxlRow++)
                        {
                            wordTable.Cell(currxlRow, currxlCol).Range.Text = xlWorkSheet.Cells[currxlRow, currxlCol].Value.ToString();
                        }
                    }
                }
            }

            //Close Excel
            xlWorkBook.Close(false, miss, miss);

            //Clear Excel Variables
            xlApp.Application.Quit();
            xlApp.Quit();

            Marshal.ReleaseComObject(xlCells);
            Marshal.ReleaseComObject(xlWorkSheet);
            Marshal.ReleaseComObject(xlWorkBook);
            Marshal.ReleaseComObject(xlApp);

            xlCells     = null;
            xlWorkSheet = null;
            xlWorkBook  = null;
            xlApp       = null;

            //Clear Word variables
            if (!showWord)
            {
                //Copy Table to Clipboard
                docs.ActiveWindow.Selection.WholeStory();
                docs.ActiveWindow.Selection.Copy();

                //Close Word
                docs.Close(SaveChanges);
                WordApp.Application.Quit(SaveChanges);
                WordApp.Quit();
            }

            Marshal.ReleaseComObject(wordTable);
            Marshal.ReleaseComObject(docs);
            Marshal.ReleaseComObject(WordApp);

            wordTable = null;
            docs      = null;
            WordApp   = null;

            GC.Collect();

            return(true);
        }