Beispiel #1
0
        /// <summary>
        /// 分离单元格
        /// </summary>
        public static void SeparateCell()
        {
            object oMissing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word._Application WordApp;
            Microsoft.Office.Interop.Word._Document    WordDoc;
            WordApp         = new Microsoft.Office.Interop.Word.Application();
            WordApp.Visible = true;
            WordDoc         = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            object start = 0;
            object end   = 0;

            Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(ref start, ref end);
            WordDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);

            Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
            object beforeRow = newTable.Rows[1];

            newTable.Rows.Add(ref beforeRow);

            Microsoft.Office.Interop.Word.Cell cell = newTable.Cell(1, 1);
            cell.Merge(newTable.Cell(1, 2));

            object Rownum    = 2;
            object Columnnum = 2;

            cell.Split(ref Rownum, ref Columnnum);
        }
Beispiel #2
0
        /// <summary>
        /// 检查单元格是否行合并过且横跨多个页面
        /// </summary>
        internal static bool IsCellMultiPagesMerged(Word.Table table, Word.Cell cell)
        {
            // 判断是否合并过?
            var cellRowSpan = GetCellRowSpan(table, cell);

            if (cellRowSpan <= 1)
            {
                return(false);
            }
            var isMultiPagesMerged = false;
            var cellPageNum        = GetCellPageNum(cell);

            // 拆分,为了解析方便
            cell.Split(NumRows: cellRowSpan);
            // 查找每个基本单元格的页码
            for (var curRowIndex = cell.RowIndex + 1; curRowIndex < cell.RowIndex + cellRowSpan; curRowIndex++)
            {
                var curCell        = table.Cell(curRowIndex, cell.ColumnIndex);
                var curCellPageNum = GetCellPageNum(curCell);
                if (curCellPageNum > cellPageNum)   // 找到某个基本单元格在另外一页
                {
                    isMultiPagesMerged = true;
                }
                // 重新合并
                cell.Merge(curCell);
            }

            return(isMultiPagesMerged);
        }
Beispiel #3
0
        /// <summary>
        /// 合并单元格
        /// </summary>
        public static void CombinationCell()
        {
            object oMissing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word._Application WordApp;
            Microsoft.Office.Interop.Word._Document    WordDoc;
            WordApp         = new Microsoft.Office.Interop.Word.Application();
            WordApp.Visible = true;
            WordDoc         = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            object start = 0;
            object end   = 0;

            Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(ref start, ref end);
            WordDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);

            Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
            object beforeRow = newTable.Rows[1];

            newTable.Rows.Add(ref beforeRow);

            Microsoft.Office.Interop.Word.Cell cell = newTable.Cell(2, 1);//2行1列合并2行2列为一起
            cell.Merge(newTable.Cell(2, 2));
            //cell.Merge( newTable.Cell( 1, 3 ) );
        }
            //---------------------------------------------------------------------------------------------------------
            /// <summary>
            /// Объединение ячеек по горизонтали
            /// </summary>
            /// <param name="cell">Ячейка</param>
            /// <param name="count">Количество объединяемых ячеек</param>
            /// <returns>Ячейка</returns>
            //---------------------------------------------------------------------------------------------------------
            public static Word.Cell MergeHorizontal(this Word.Cell cell, Int32 count = 1)
            {
                Int32 row_index     = cell.RowIndex;
                Int32 collumn_index = cell.ColumnIndex;

                Word.Table table_owner = cell.Parent as Word.Table;
                cell.Merge(table_owner.Cell(row_index, collumn_index + count));
                return(cell);
            }
Beispiel #5
0
 // Merge several column into one column
 public void MergeColumn(Word.Table tb, Word.Cell[] cells)
 {
     if (cells.Length > 1)
     {
         Word.Cell c   = cells[0];
         int       len = cells.Length;
         for (int i = 1; i < len; i++)
         {
             c.Merge(cells[i]);
         }
     }
     wordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
 }
Beispiel #6
0
        private void MakeHeader(Table table)
        {
            Microsoft.Office.Interop.Word.Row  row       = table.Rows[1];
            Microsoft.Office.Interop.Word.Cell firstCell = row.Cells[1];
            foreach (Microsoft.Office.Interop.Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }
            firstCell.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalTop;
            Range nameTableRange = table.Cell(1, 1).Range;

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

            for (int i = 0; i < table.Columns.Count; i++)
            {
                headerRange      = table.Cell(2, i + 1).Range;
                headerRange.Text = columns[i];
            }
        }
Beispiel #7
0
        public void SetCellsMerge(int FirstColumn, int LastColumn, int FirstRow, int LastRow, MSWord.WdCellVerticalAlignment vAlignment, int indTable = -1)
        {
            if (FirstColumn == LastColumn && FirstRow == LastRow)
            {
                return;
            }

            GetTableReference(indTable);

            MSWord.Cell pCellBegin = m_pTable.Cell(FirstRow, FirstColumn);
            MSWord.Cell pCellEnd   = m_pTable.Cell(LastRow, LastColumn);
            if (pCellBegin == null)
            {
                return;
            }
            if (pCellEnd == null)
            {
                return;
            }

            pCellBegin.Merge(pCellEnd);
            pCellBegin.VerticalAlignment = vAlignment;
        }
Beispiel #8
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var t = e.Argument as Tuple <string, string>;

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

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

            DataSet ds1 = new DataSet();

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

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

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

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

            int columnsCount = 5;

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

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

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

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

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


            int rowCount  = 3;
            int rowNumber = 0;

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

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

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

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

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

            wdApp.Visible = true; //показать документ пользователю
        }
Beispiel #9
0
        public void PrintForm4()
        {
            string select = @"SELECT [Group].groupName, count(Student.name)
                              FROM Student INNER JOIN
                              [Group] ON Student.idGroup = [Group].id
                              WHERE ((Student.id_comm = 2) AND (prikazNumKval = '') AND (prikazNumOut = '')) 
                              GROUP BY groupName";

            DataSet ds1 = new DataSet();

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

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

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

            int columnsCount = 4;

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

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

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

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

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


            int rowCount  = 3;
            int rowNumber = 0;

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

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

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

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

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

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

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

            if (t.Item2 == "")
            {
                MessageBox.Show("Военкомат не задан!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            //здесь формирование ворд-документа
            string select = @"SELECT Student.name, Student.birth, Student.ciizenship, Student.passpSeries, Student.passpNumber, 
                                     [Group].groupName, Student.street, Student.house, Student.flat, Student.phone, sex.sex, district.district, Student.homePhone
                              FROM Student INNER JOIN
                                   [Group] ON Student.idGroup = [Group].id INNER JOIN
                                   sex ON Student.id_sex = sex.id INNER JOIN
                                   district ON Student.id_district = district.id
                              WHERE (Student.birth LIKE '%" + t.Item1 + @"%') AND 
                                    (sex.sex = 'муж.') AND 
                                    ((prikazNumKval = '') AND (prikazNumOut = '')) AND ";

            select += ConvertDistrictNameToDistrictQuery(t.Item2);
            select += @" ORDER BY name";

            DataSet ds1 = new DataSet();

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

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

            voenkomat = ConvertVoencomatNameToFullName(t.Item2);

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

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

            int columnsCount = 6;

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

            tb.Rows[1].Height = 40;
            tb.Rows[2].Height = 70;
            tb.Rows[4].Height = 30;
            tb.Rows[5].Height = 40;

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

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

            tb.Cell(1, 1).Select();
            //wdApp.Selection.Range.Font.Size = 12;
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            tb.Cell(1, 1).Range.Text = "Приложение №3 \n к инструкции (п.п.9,20) \n Калининский район";

            tb.Rows[3].Select();
            //wdApp.Selection.Range.Font.Size = 12;
            wdApp.Selection.Font.Bold = 1;
            tb.Cell(3, 1).Range.Text  = "СПИСОК";
            tb.Rows[4].Select();
            wdApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalTop;
            tb.Cell(4, 1).Range.Text = "Граждан " + t.Item1 + " года рождения, зарегистрированных и проживающих на территории " + voenkomat;

            tb.Rows[5].Select();
            wdApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalTop;
            tb.Cell(5, 1).Range.Text = @" ";
            tb.Rows[6].Select();
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            tb.Cell(6, 1).Range.Text = "№ п/п";
            tb.Cell(6, 2).Range.Text = "Фамилия, имя, отчество";
            tb.Cell(6, 3).Range.Text = "Гражданство \n серия и номер паспорта";
            tb.Cell(6, 4).Range.Text = "Место работы (учебы) и занимаемая должность (курс, класс)";
            tb.Cell(6, 5).Range.Text = "Зарегистрированние место жительства, номер телефона (если проживает по другому адресу, указывается место проживания, номер телефона)";
            tb.Cell(6, 6).Range.Text = "Отметка военного комиссариата. За каким порядковым номером учтен в сводном списке.";


            int rowCount  = 6;
            int rowNumber = 0;

            foreach (DataRow str in ds1.Tables[0].Rows)
            {
                rowCount++;
                rowNumber++;
                tb.Cell(rowCount, 1).Range.Text = rowNumber.ToString() + ".";
                tb.Cell(rowCount, 2).Range.Text = str.ItemArray[0].ToString() + "\n" + DateTime.Parse(str.ItemArray[1].ToString()).ToShortDateString();
                tb.Cell(rowCount, 3).Range.Text = str.ItemArray[2].ToString() + "\n" + str.ItemArray[3].ToString() + " " + str.ItemArray[4].ToString();
                //tb.Cell(rowCount, 3).Range.Text = DateTime.Parse(str.ItemArray[1].ToString()).ToShortDateString(); //номер курса считать
                tb.Cell(rowCount, 4).Range.Text = "  \n" + Util.CalcKurs(str.ItemArray[5].ToString()) + " курс, уч-ся гр. " + str.ItemArray[5].ToString();
                tb.Cell(rowCount, 5).Range.Text = "ул. " + str.ItemArray[6].ToString() + ", " + str.ItemArray[7].ToString() + " кв. " + str.ItemArray[8].ToString() + "\n"
                                                  + str.ItemArray[11].ToString() + " р-н \n Тел. " + str.ItemArray[9].ToString() + " \n Дом. " + str.ItemArray[12].ToString();
            }

            _range = wdDoc.Range(tb.Cell(7, 2).Range.Start, tb.Cell(rowCount, columnsCount).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wdApp.Selection.Cells.VerticalAlignment   = Word.WdCellVerticalAlignment.wdCellAlignVerticalTop;
            _range = wdDoc.Range(tb.Cell(7, 3).Range.Start, tb.Cell(rowCount, 3).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            _range = wdDoc.Range(tb.Cell(6, 1).Range.Start, tb.Cell(rowCount, columnsCount).Range.End);
            _range.Select();

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


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

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

            tb2.Columns[1].Width = 140;
            tb2.Columns[2].Width = 120;
            tb2.Columns[3].Width = 380;
            tb2.Columns[4].Width = 100;

            tb2.Rows[1].Height = 30;
            tb2.Rows[2].Height = 30;

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

            _range = wdDoc.Range(tb2.Cell(3, 2).Range.Start, tb2.Cell(3, 4).Range.End);
            _range.Select();
            wdApp.Selection.Cells.Merge();

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

            //tb2.Cell(2, 2).Range.Text = "«" + DateTime.Now.Day.ToString() + "»" + DateTime.Now.Month.ToString("MMMM") + " " + DateTime.Now.Year.ToString() + " г.";
            tb2.Cell(2, 2).Range.Text = DateTime.Now.ToLongDateString().ToString();
            tb2.Cell(3, 1).Range.Text = "    М.П.";
            tb2.Cell(3, 2).Range.Text = "Должностное лицо, отвечающее за ведение воинского учёта   контактный телефон  ";

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

            wdApp.Visible = true; //показать документ пользователю
        }
Beispiel #11
0
        public string PrintPDF(int PDFId, out string QPNo, out string GuidNO, string modelWordUrl, string wordUrl)
        {
            //ServiceAppSetting.LoggerHander("开始转换", "");
            QPNo   = "";
            GuidNO = "";
            //string modelWordUrl = System.Web.HttpContext.Current.Request.MapPath("WordModel/") + "QP.doc";
            //if (!File.Exists(modelWordUrl))
            //{
            //    base.ClientScript.RegisterStartupScript(base.GetType(), null, "<script>alert('模版不存在!');</script>");
            //    return "";
            //}
            tb_QuotePriceService QuotePriSer = new tb_QuotePriceService();

            tb_QuotePrice model = QuotePriSer.GetModel(PDFId);

            //ServiceAppSetting.LoggerHander("获取实体", "");
            if (model.QPType == 2)//不含税 英文模版
            {
                modelWordUrl = modelWordUrl.Replace("QP", "EnQP");
            }

            GuidNO = model.QuoteNo;

            string guidUrl = wordUrl + GuidNO + ".doc";

            if (!File.Exists(guidUrl))
            {
                File.Copy(modelWordUrl, guidUrl);
            }
            else
            {
                return(guidUrl);
            }
            //ServiceAppSetting.LoggerHander("复制文件", "");
            Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();

            object oMissing = System.Reflection.Missing.Value;
            //打开模板文档,并指定doc的文档类型
            object objTemplate = guidUrl;
            //路径一定要正确
            object objDocType       = WdDocumentType.wdTypeDocument;
            object objfalse         = false;
            object objtrue          = true;
            object miss             = System.Reflection.Missing.Value;
            object missingValue     = Type.Missing;
            object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;

            Microsoft.Office.Interop.Word.Document doc = null;
            try
            {
                try
                {
                    //ServiceAppSetting.LoggerHander("开始创建模版", "");
                    doc = (Document)appWord.Documents.Add(ref objTemplate, ref objfalse, ref objDocType, ref objtrue);
                    //ServiceAppSetting.LoggerHander("结束创建模版", "");
                }
                catch (Exception ex)
                {
                }

                //获取模板中所有的书签
                Bookmarks odf = doc.Bookmarks;


                QPNo = model.QuoteNo;
                Dictionary <string, string> bookMarks = new Dictionary <string, string>();
                bookMarks.Add("QuoteNo", model.QuoteNo);
                bookMarks.Add("QuoteNo1", model.QuoteNo);
                bookMarks.Add("GuestNo", model.GuestNo);
                bookMarks.Add("QuoteDate", model.QuoteDate.ToString("yyyy-MM-dd"));
                bookMarks.Add("ResultGuestName", model.ResultGuestName);
                bookMarks.Add("GuestName2", model.GuestName);
                bookMarks.Add("ResultGuestNo", model.ResultGuestNo);
                bookMarks.Add("PayStyle", model.PayStyle);
                bookMarks.Add("ContactPerToInv", model.ContactPerToInv);
                bookMarks.Add("NaShuiPer", model.NaShuiPer);
                //telToInv
                bookMarks.Add("telToInv", model.telToInv);
                //InvoHeader
                bookMarks.Add("InvoHeader", model.InvoHeader);
                //brandNo
                bookMarks.Add("brandNo", model.brandNo);
                //GuestNameToInv
                bookMarks.Add("GuestNameToInv", model.GuestNameToInv);
                //InvAddress
                bookMarks.Add("InvAddress", model.InvAddress);
                //AddressTofa
                bookMarks.Add("AddressTofa", model.AddressTofa);
                //AddressToInv
                bookMarks.Add("AddressToInv", model.AddressToInv);
                //InvTel
                bookMarks.Add("InvTel", model.InvTel);
                //InvContactPer
                bookMarks.Add("InvContactPer", model.InvContactPer);
                //BuessName
                bookMarks.Add("BuessName", model.BuessName);
                //ComBusTel
                bookMarks.Add("ComBusTel", model.ComBusTel);
                //ComTel
                bookMarks.Add("ComTel", model.ComTel);
                //BuessEmail
                bookMarks.Add("BuessEmail", model.BuessEmail);
                //ComChuanZhen
                bookMarks.Add("ComChuanZhen", model.ComChuanZhen);

                //ZLBZ
                bookMarks.Add("ZLBZ", model.ZLBZ);
                //YSBJ
                bookMarks.Add("YSBJ", model.YSBJ);
                //FWBXDJ
                bookMarks.Add("FWBXDJ", model.FWBXDJ);
                //JFQ
                bookMarks.Add("JFQ", model.JFQ);
                //ComName
                bookMarks.Add("ComName", model.ComName);
                //ComBrand
                bookMarks.Add("ComBrand", model.ComBrand);
                //ComBrand
                bookMarks.Add("Zhanghao", model.Address);
                //NaShuiNo
                bookMarks.Add("NaShuiNo", model.NaShuiNo);

                if (model.IsYH)
                {
                    //NaShuiNo
                    bookMarks.Add("YHPrice", model.LastYH.ToString());
                }
                foreach (var key in bookMarks.Keys)
                {
                    try
                    {
                        object objKey = key;
                        doc.Bookmarks.get_Item(ref objKey).Range.Text = bookMarks[key];
                    }
                    catch (Exception)
                    {
                    }
                }
                //ServiceAppSetting.LoggerHander("书签 赋值", "");
                ////修改图片
                //object YHPrice = "YHPrice";
                //var xShape =doc.Bookmarks.get_Item(ref YHPrice).Range.InlineShapes.AddPicture(@"C:\Users\fj3174\Desktop\1.bmp", false, true ) ;

                //doc.Bookmarks.get_Item(ref YHPrice).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                //报价内容
                Microsoft.Office.Interop.Word.Table nowTable = doc.Tables[2];


                Object Nothing = System.Reflection.Missing.Value;

                tb_QuotePrice_InvDetailsService invDetailSer = new tb_QuotePrice_InvDetailsService();
                List <tb_QuotePrice_InvDetails> invDetails   = invDetailSer.GetListArray(" QuoteId=" + PDFId);

                //invDetails.Add(new tb_QuotePrice_InvDetails { });
                decimal total = 0;

                for (int i = 0; i < invDetails.Count; i++)
                {
                    invDetails[i].No = i + 1;
                    total           += invDetails[i].Total;
                    nowTable.Rows.Add(ref Nothing);
                }



                int rowsCount   = nowTable.Rows.Count;
                int columnCount = nowTable.Columns.Count;

                decimal fax       = Convert.ToDecimal(1.17);
                decimal noHanShui = 0;
                if (invDetails.Count > 0)
                {
                    for (int rowPos = 2; rowPos <= rowsCount; rowPos++)
                    {
                        try
                        {
                            if (model.QPType == 2)
                            {
                                nowTable.Cell(rowPos, 1).Range.Text = invDetails[rowPos - 2].No.ToString();
                                nowTable.Cell(rowPos, 2).Range.Text = invDetails[rowPos - 2].InvName.ToString();
                                nowTable.Cell(rowPos, 3).Range.Text = invDetails[rowPos - 2].InvModel.ToString();
                                nowTable.Cell(rowPos, 4).Range.Text = invDetails[rowPos - 2].InvUnit.ToString();
                                nowTable.Cell(rowPos, 5).Range.Text = string.Format("{0:n0}", invDetails[rowPos - 2].InvNum);
                                nowTable.Cell(rowPos, 6).Range.Text = string.Format("{0:n2}", (invDetails[rowPos - 2].InvPrice / fax));
                                noHanShui += (invDetails[rowPos - 2].InvPrice / fax) * invDetails[rowPos - 2].InvNum;
                                nowTable.Cell(rowPos, 7).Range.Text = string.Format("{0:n2}", invDetails[rowPos - 2].InvPrice);
                                nowTable.Cell(rowPos, 8).Range.Text = string.Format("{0:n2}", invDetails[rowPos - 2].Total);
                                if (model.IsBrand)
                                {
                                    nowTable.Cell(rowPos, 9).Range.Text = invDetails[rowPos - 2].GoodBrand.ToString();//品牌
                                }
                                else
                                {
                                    nowTable.Cell(rowPos, 9).Range.Text = "";//品牌
                                }
                                if (model.IsProduct)
                                {
                                    nowTable.Cell(rowPos, 10).Range.Text = invDetails[rowPos - 2].Product.ToString();//产地
                                }
                                else
                                {
                                    nowTable.Cell(rowPos, 10).Range.Text = "";//产地
                                }
                                if (model.IsRemark)
                                {
                                    nowTable.Cell(rowPos, 11).Range.Text = invDetails[rowPos - 2].InvRemark.ToString();//备注
                                }
                                else
                                {
                                    nowTable.Cell(rowPos, 11).Range.Text = "";//备注
                                }
                            }
                            else
                            {
                                nowTable.Cell(rowPos, 1).Range.Text = invDetails[rowPos - 2].No.ToString();
                                nowTable.Cell(rowPos, 2).Range.Text = invDetails[rowPos - 2].InvName.ToString();
                                nowTable.Cell(rowPos, 3).Range.Text = invDetails[rowPos - 2].InvModel.ToString();
                                nowTable.Cell(rowPos, 4).Range.Text = invDetails[rowPos - 2].InvUnit.ToString();
                                nowTable.Cell(rowPos, 5).Range.Text = string.Format("{0:n0}", invDetails[rowPos - 2].InvNum);
                                nowTable.Cell(rowPos, 6).Range.Text = string.Format("{0:n2}", invDetails[rowPos - 2].InvPrice);
                                nowTable.Cell(rowPos, 7).Range.Text = string.Format("{0:n2}", invDetails[rowPos - 2].Total);
                                if (model.IsBrand)
                                {
                                    nowTable.Cell(rowPos, 8).Range.Text = invDetails[rowPos - 2].GoodBrand.ToString();
                                }
                                else
                                {
                                    nowTable.Cell(rowPos, 8).Range.Text = "";//品牌
                                }
                                if (model.IsProduct)
                                {
                                    nowTable.Cell(rowPos, 9).Range.Text = invDetails[rowPos - 2].Product.ToString();
                                }
                                else
                                {
                                    nowTable.Cell(rowPos, 9).Range.Text = "";//产地
                                }
                                if (model.IsRemark)
                                {
                                    nowTable.Cell(rowPos, 10).Range.Text = invDetails[rowPos - 2].InvRemark.ToString();
                                }
                                else
                                {
                                    nowTable.Cell(rowPos, 10).Range.Text = "";//备注
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }


                //合计

                if (model.QPType == 3)//工程 加三行
                {
                    //材料小计
                    nowTable.Rows.Add(ref Nothing);

                    nowTable.Cell(rowsCount, 6).Range.Text = "材料小计";
                    nowTable.Cell(rowsCount, 7).Range.Text = total.ToString();
                    //人工费用
                    nowTable.Rows.Add(ref Nothing);
                    rowsCount++;
                    nowTable.Cell(rowsCount, 6).Range.Text = "人工费用";
                    nowTable.Cell(rowsCount, 7).Range.Text = model.LaborCost.ToString();
                    nowTable.Cell(rowsCount, 7).Range.Shading.ForegroundPatternColor = WdColor.wdColorYellow;//背景颜色
                    total += model.LaborCost;
                    //工程计税
                    nowTable.Rows.Add(ref Nothing);
                    rowsCount++;
                    nowTable.Cell(rowsCount, 6).Range.Text = "工程计税";
                    nowTable.Cell(rowsCount, 7).Range.Text = model.EngineeringTax.ToString();
                    nowTable.Cell(rowsCount, 7).Range.Shading.ForegroundPatternColor = WdColor.wdColorYellow;//背景颜色
                    total += model.EngineeringTax;
                }

                if (model.QPType == 2)                                                          //不含税 英文格式 加1行
                {
                    Microsoft.Office.Interop.Word.Cell cell1 = nowTable.Cell(rowsCount + 1, 2); //2行1列合并2行2列为一起
                    cell1.Merge(nowTable.Cell(rowsCount + 1, 7));
                    nowTable.Cell(rowsCount + 1, 2).Range.Text = "总计人民币(不含税):  " + string.Format("CNY {0:n2}", noHanShui) + System.Environment.NewLine +
                                                                 "总计人民币增值税:      " + string.Format("CNY {0:n2}", (total - noHanShui));
                    nowTable.Cell(rowsCount + 1, 2).LeftPadding = 2;
                    nowTable.Cell(rowsCount + 1, 2).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    rowsCount++;
                    nowTable.Rows.Add(ref Nothing);
                }
                if (model.QPType != 2)
                {
                    Microsoft.Office.Interop.Word.Cell cell = nowTable.Cell(rowsCount + 1, 2);//2行1列合并2行2列为一起
                    cell.Merge(nowTable.Cell(rowsCount + 1, 6));

                    nowTable.Cell(rowsCount + 1, 2).Range.Text = "总计人民币(含税):";

                    nowTable.Cell(rowsCount + 1, 2).LeftPadding = 2;
                    float size = 10.5f;
                    //app.Selection.Font.Size
                    nowTable.Cell(rowsCount + 1, 2).Range.Font.Size = size;
                    nowTable.Cell(rowsCount + 1, 3).Range.Font.Size = size;
                    nowTable.Cell(rowsCount + 1, 2).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

                    nowTable.Cell(rowsCount + 1, 3).Range.Text = string.Format("CNY {0:n2}", total);

                    nowTable.Cell(rowsCount + 1, 2).Range.Bold = 2; //设置单元格中字体为粗体
                    nowTable.Cell(rowsCount + 1, 3).Range.Bold = 2; //设置单元格中字体为粗体
                }
                else
                {
                    nowTable.Cell(rowsCount + 1, 2).Range.Text = "总计人民币(含税):      " + string.Format("CNY {0:n2}", total);

                    nowTable.Cell(rowsCount + 1, 2).LeftPadding = 2;
                    float size = 10.5f;
                    //app.Selection.Font.Size
                    nowTable.Cell(rowsCount + 1, 2).Range.Font.Size = size;
                    //nowTable.Cell(rowsCount + 1, 3).Range.Font.Size = size;
                    nowTable.Cell(rowsCount + 1, 2).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

                    //nowTable.Cell(rowsCount + 1, 3).Range.Text = string.Format("CNY {0:n2}", total);

                    nowTable.Cell(rowsCount + 1, 2).Range.Bold = 2;//设置单元格中字体为粗体
                    //nowTable.Cell(rowsCount + 1, 3).Range.Bold = 2;//设置单元格中字体为粗体
                }

                if (model.IsYH)//增加最后优惠信息
                {
                    //人工费用
                    nowTable.Rows.Add(ref Nothing);

                    rowsCount++;

                    Microsoft.Office.Interop.Word.Cell cell = nowTable.Cell(rowsCount + 1, 2);//2行1列合并2行2列为一起
                    //cell.Merge(nowTable.Cell(rowsCount + 1, 6));
                    if (model.QPType == 2)
                    {
                        nowTable.Cell(rowsCount + 1, 2).Range.Text = "最终优惠价(含税):      " + string.Format("CNY {0:n2}", model.LastYH);
                    }
                    else
                    {
                        nowTable.Cell(rowsCount + 1, 2).Range.Text = "最终优惠价(含税):";
                    }

                    nowTable.Cell(rowsCount + 1, 2).LeftPadding = 2;
                    float size = 10.5f;
                    //app.Selection.Font.Size
                    nowTable.Cell(rowsCount + 1, 2).Range.Font.Size = size;
                    nowTable.Cell(rowsCount + 1, 3).Range.Font.Size = size;
                    nowTable.Cell(rowsCount + 1, 2).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    if (model.QPType != 2)
                    {
                        nowTable.Cell(rowsCount + 1, 3).Range.Text = string.Format("CNY {0:n2}", model.LastYH);
                    }
                    nowTable.Cell(rowsCount + 1, 2).Range.Bold = 2; //设置单元格中字体为粗体
                    nowTable.Cell(rowsCount + 1, 3).Range.Bold = 2; //设置单元格中字体为粗体
                }

                //object objKey_Total = "Total";
                //doc.Bookmarks.get_Item(ref objKey_Total).Range.Text = string.Format("{0:n2}", total);

                doc.SaveAs(ref objTemplate, ref miss, ref miss, ref miss, ref miss, ref miss,
                           ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
                appWord.Application.Quit(ref miss, ref miss, ref miss);
                doc     = null;
                appWord = null;
            }
            catch (Exception ex)
            {
                // base.ClientScript.RegisterStartupScript(base.GetType(), null, "<script>alert('文件不存在!');</script>");
                doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
                appWord.Application.Quit(ref miss, ref miss, ref miss);
                if (System.IO.File.Exists(objTemplate.ToString()))
                {
                    try
                    {
                        System.IO.File.Delete(objTemplate.ToString());
                    }
                    catch (Exception)
                    {
                    }
                }

                return("");
            }
            return(objTemplate.ToString());
        }
Beispiel #12
0
        private int TestExcelToWord(word.Document document, ISheet sheet, string bookmarks, IWorkbook workbook, int firstrowno, int lastrowno, int rowdatastart, int columnscount, bool isdelnull = true, int fixedcolumn = 4)
        {
            //表格行
            int iRowscount = lastrowno;

            //获取标签
            word.Bookmark bsbk    = document.Bookmarks[bookmarks];
            word.Range    bsrange = bsbk.Range;
            //表格列
            int iColumnscount = columnscount;

            //去掉上面的行数   数据开始的行号   数据结束的列号
            int iRowStart = firstrowno, iRowDataStart = rowdatastart, iColumDataStart = 2;

            //发生过异动的行号
            List <int> lstRowsno = new List <int>();
            //发生过异动的行号
            List <int> lstColumnsno = new List <int>();

            try
            {
                //循环sheet  然后后删除 这行是记录新旧编号的对应关系的
                Dictionary <int, int> dicOldNewColumn = new Dictionary <int, int>();
                //获取sheet原本信息
                var vdic = GetSheetInfo(sheet, iRowscount, iRowStart, iColumnscount, out Dictionary <int, List <rowcolumMerge> > dicmerge, dicOldNewColumn, false);

                Dictionary <int, List <string> > _lstmainvdic = new Dictionary <int, List <string> >(vdic);
                Dictionary <int, List <string> > _lsttempvdic = new Dictionary <int, List <string> >(vdic);

                //如何有合并  就删除空行列和调整行列编号
                if (dicmerge.Count > 0)
                {
                    vdic = GetNotAllRowNull(iRowDataStart, iColumDataStart, vdic, out lstRowsno);
                    vdic = GetNotAllColumnNull(iRowDataStart, iColumDataStart, vdic, out lstColumnsno, iRowStart, _lsttempvdic, out dicOldNewColumn, true);

                    if (lstRowsno.Count > 0)
                    {
                        //开始处理合并信息 调整行次列次
                        GetRowMerge(lstRowsno, dicmerge, iRowStart);
                    }
                    if (lstColumnsno.Count > 0)
                    {
                        GetColumnMerge(lstColumnsno, dicmerge);
                    }
                }

                //生成 doc 表格
                word.Table tbl = bsrange.Tables.Add(bsrange, vdic.Count, vdic[iRowStart].Count);

                for (int columnno = 0; columnno < vdic[iRowStart].Count; columnno++)
                {
                    tbl.Columns[columnno + 1].Width = 30;
                }

                //表格的外边框显示
                tbl.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                ////表格的内边框显示
                tbl.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;

                //开始进行处理段落
                word.Paragraph tblpa;
                //单元格值
                var vCelltext = "";

                //计数  行次         实际的列
                int iHC = iRowStart, iRealColumncount = 0;

                int iCellRowno = 0, iCellColumno = 0;

                int iMergeColumn = 0;               //合并列的信息行信息

                bool bFlag = true, bFlagRow = true; //标记是否需要继续列合并 行合并

                Dictionary <int, List <ColumnSpan> > _cs = new Dictionary <int, List <ColumnSpan> >();
                List <ColumnSpan>       columnSpans      = new List <ColumnSpan>();
                NPOI.SS.UserModel.ICell iCell            = null;
                bool fzFlag = false;


                /*将上年金额显示在表格下方:
                 * 1、找到上年金额所在的列 到此列开始   不在进行表格输入
                 * 2、修改合并的信息
                 * 3、组table 放在上年的表格下方  空一行   最后再把这行删掉*/

                foreach (int keys in vdic.Keys)
                {
                    iMergeColumn = 0;
                    // iLastColumnno = 0;
                    iRealColumncount = 0;

                    bFlagRow    = true;
                    fzFlag      = false;
                    columnSpans = new List <ColumnSpan>();
                    for (int columnno = 0; columnno < vdic[iRowStart].Count; columnno++)
                    {
                        ColumnSpan _objcolumnSpan = new ColumnSpan();
                        bFlag = true;
                        //初始情况或者是列大于这个合并的列
                        if ((iMergeColumn == 0 || columnno >= iMergeColumn) && iMergeColumn < vdic[keys].Count)
                        {
                            vCelltext = vdic[keys][columnno];

                            //单元格 字段 范围  书签
                            //如果系数大于1   由于标题重复原因  是从第四行开始读  所以需要rowno-1才是标签位置
                            iCellRowno   = iHC - iRowStart + 1;
                            iCellColumno = iRealColumncount + 1;

                            word.Cell      _wCell = tbl.Cell(iCellRowno, iCellColumno);
                            word.Paragraph cpara  = _wCell.Range.Paragraphs.First;
                            word.Range     range  = _wCell.Range;
                            word.Bookmark  bookm  = range.Bookmarks.Add(bookmarks + "_" + iCellRowno + "_" + iCellColumno);

                            //对应excel中的单元格  如果设置格式  比如对齐方式  或者是否加粗 可通过icell获取
                            iCell = sheet.GetRow(keys).GetCell(dicOldNewColumn[columnno], MissingCellPolicy.CREATE_NULL_AS_BLANK);
                            //获取对应excel中的单元格 样式
                            ICellStyle cellStyle = iCell.CellStyle;
                            IFont      font      = cellStyle.GetFont(workbook);

                            if (font.IsBold)
                            {
                                range.Font.Bold = font.Boldweight;
                            }
                            range.Font.Name = font.FontName;
                            range.Font.Size = 4;

                            word.Range _range = cpara.Range;
                            _range.Font.Name = font.FontName;
                            _range.Text      = vCelltext;

                            int icsRowspan = 0;             //初始状态
                                                            //对单元格进行合并 列合并
                            if (dicmerge.ContainsKey(keys)) //说明这行有需要合并的
                            {
                                dicmerge.Where(x => x.Key == keys).ToList()
                                .ForEach(gg =>
                                {
                                    if (bFlag)    //如果这列没有合并过  如果这列已经合并  不需要走以下代码
                                    {
                                        dicmerge[gg.Key].ForEach(w =>
                                        {
                                            //合并列>1 需要合并 有列需要合并
                                            if (w.ColumnSpan > 1 && bFlag)    //ocolumnindex
                                            {
                                                if (columnno >= w.FirstColumnIndex && columnno <= w.LastColumnIndex)
                                                {
                                                    try
                                                    {
                                                        //得到列信息 之后列循环   凡是坐落在此区间的   不再进行合并
                                                        iMergeColumn = columnno + w.ColumnSpan;
                                                        //iLastColumnno = columnno;
                                                        var ss = tbl.Cell(iCellRowno, iRealColumncount + w.ColumnSpan);
                                                        _wCell.Merge(ss);
                                                        //合并后居中
                                                        _wCell = tbl.Cell(iCellRowno, iCellColumno);
                                                        cpara  = _wCell.Range.Paragraphs.First;

                                                        _wCell.VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                                                        cpara.Alignment          = word.WdParagraphAlignment.wdAlignParagraphCenter;

                                                        _objcolumnSpan.Columnno = iCellColumno;
                                                        icsRowspan                      = w.RowSpan;
                                                        _objcolumnSpan.Rowspan          = w.RowSpan;
                                                        _objcolumnSpan.FirstRowIndex    = w.FirstRowIndex;
                                                        _objcolumnSpan.LastRowIndex     = w.LastRowIndex;
                                                        _objcolumnSpan.Columnno         = iCellColumno;
                                                        _objcolumnSpan.LastColumnIndex  = w.LastColumnIndex;
                                                        _objcolumnSpan.FirstColumnIndex = w.FirstColumnIndex;
                                                        //单元格合并之后  需要把合并的单元格的列号进行更新  方便进行行合并
                                                        bFlag = false;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        MessageBox.Show(ex.Message + "||" + ex.StackTrace.ToString(), "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                    }
                                                }
                                            }
                                        });
                                    }
                                });
                            }

                            if (icsRowspan == 0 && bFlag && dicmerge.ContainsKey(keys))//没有进行合并   找到对应的rowspan  用实际的columnno
                            {
                                bool isXH = true;

                                dicmerge[keys].ForEach(gg =>
                                {
                                    if (columnno >= gg.FirstColumnIndex && columnno <= gg.LastColumnIndex && isXH)
                                    {
                                        //在区间
                                        _objcolumnSpan.Rowspan          = gg.RowSpan;
                                        _objcolumnSpan.FirstRowIndex    = gg.FirstRowIndex;
                                        _objcolumnSpan.LastRowIndex     = gg.LastRowIndex;
                                        _objcolumnSpan.Columnno         = iCellColumno;
                                        _objcolumnSpan.LastColumnIndex  = gg.LastColumnIndex;
                                        _objcolumnSpan.FirstColumnIndex = gg.FirstColumnIndex;
                                        isXH = false;
                                    }
                                });
                            }

                            iRealColumncount++;
                            columnSpans.Add(_objcolumnSpan);
                        }
                    }
                    iHC++;
                    _cs[iCellRowno] = columnSpans;
                }

                columnSpans = new List <ColumnSpan>();
                Dictionary <string, string> _dictemp = new Dictionary <string, string>();

                //处理行合并
                foreach (int irowsno in _cs.Keys)
                {
                    columnSpans = _cs[irowsno];

                    if (columnSpans.Count > 0)
                    {
                        //循环合并
                        columnSpans.ForEach(x =>
                        {
                            if (x.Rowspan > 1 && x.LastColumnIndex < vdic[iRowStart].Count)
                            {
                                //判断是否已经合并过了
                                if (!_dictemp.ContainsKey(x.FirstRowIndex + "||" + x.LastRowIndex + "||" + x.LastColumnIndex + "||" + x.FirstColumnIndex))
                                {
                                    tbl.Cell(irowsno, x.Columnno).Merge(tbl.Cell(x.LastRowIndex - iRowStart + 1, x.LastColumnIndex + 1));//irowsno + x.Rowspan - 1
                                    _dictemp[x.FirstRowIndex + "||" + x.LastRowIndex + "||" + x.LastColumnIndex + "||" + x.FirstColumnIndex] = "";
                                }
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                if (workbook != null)
                {
                    workbook.Close();
                }
                GC.Collect();
                MessageBox.Show(ex.Message + "||" + ex.StackTrace.ToString(), "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (workbook != null)
                {
                    workbook.Close();
                }
                GC.Collect();
            }

            return(1);
        }
Beispiel #13
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var t = e.Argument as Tuple <string, string, string, string>;

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

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

            DataSet ds1 = new DataSet();

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

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

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

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

            int columnsCount = 5;

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

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

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

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

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


            int rowCount  = 3;
            int rowNumber = 0;

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

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

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


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

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

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

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

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

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

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

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

            wdApp.Visible = true; //показать документ пользователю
        }
Beispiel #14
0
        public static bool CreateWordDocParagraph(string qname, string[][] qdata, IVsThreadedWaitDialog2 dlg)
        {
            //InitializeVariables();
            System.Net.WebClient webclient = new System.Net.WebClient();
            webclient.Credentials = System.Net.CredentialCache.DefaultCredentials;

            var           application = new MSWord.Application();
            var           document    = new MSWord.Document();
            object        missing     = System.Reflection.Missing.Value;
            int           pagewidth   = 800;
            bool          bcanceled;
            int           progress = 1;
            StringBuilder strbld   = new StringBuilder();

            MSWord.WdBuiltinStyle[] hstyles = new MSWord.WdBuiltinStyle[8];
            hstyles[0] = MSWord.WdBuiltinStyle.wdStyleHeading1;
            hstyles[1] = MSWord.WdBuiltinStyle.wdStyleHeading2;
            hstyles[2] = MSWord.WdBuiltinStyle.wdStyleHeading3;
            hstyles[3] = MSWord.WdBuiltinStyle.wdStyleHeading4;
            hstyles[4] = MSWord.WdBuiltinStyle.wdStyleHeading5;
            hstyles[5] = MSWord.WdBuiltinStyle.wdStyleHeading6;
            hstyles[6] = MSWord.WdBuiltinStyle.wdStyleHeading7;
            hstyles[7] = MSWord.WdBuiltinStyle.wdStyleHeading8;

            application.Visible       = true;
            application.WindowState   = MSWord.WdWindowState.wdWindowStateMinimize;
            application.DisplayAlerts = MSWord.WdAlertLevel.wdAlertsNone;
            document = application.Documents.Add();
            //document.PageSetup.Orientation = MSWord.WdOrientation.wdOrientLandscape;
            document.PageSetup.LeftMargin   = 20;
            document.PageSetup.RightMargin  = 20;
            document.PageSetup.TopMargin    = 20;
            document.PageSetup.BottomMargin = 20;
            document.PageSetup.PageWidth    = pagewidth + 40;

            MSWord.Paragraph prg = document.Paragraphs.Add();
            prg.Range.Text = "Query results for " + qname + " [" + DateTime.Now + "]";
            prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTitle);
            //prg.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            prg.SpaceAfter  = 100;
            prg.SpaceBefore = 100;
            prg.Range.InsertParagraphAfter();

            prg            = document.Paragraphs.Add();
            prg.Range.Text = "Table of Contents";
            prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTocHeading);
            prg.Range.InsertParagraphAfter();

            prg            = document.Paragraphs.Add();
            prg.Range.Text = "TOC";
            prg.Range.InsertParagraphAfter();
            prg.Range.InsertBreak(MSWord.WdBreakType.wdPageBreak);

            prg = document.Paragraphs.Add();
            MSWord.Table qtable = document.Tables.Add(prg.Range, qdata.Length, 1);
            prg.Range.InsertParagraphAfter();

            prg            = document.Paragraphs.Add();
            prg.Range.Text = "Appendix";
            prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTitle);
            prg.Range.InsertParagraphAfter();

            object styleTypeTable = MSWord.WdStyleType.wdStyleTypeTable;

            MSWord.Style styl = document.Styles.Add("New Table Style", ref styleTypeTable);
            styl.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceSingle;
            styl.ParagraphFormat.SpaceAfter      = 0;
            styl.ParagraphFormat.SpaceBefore     = 0;
            styl.Table.TopPadding    = 0;
            styl.Table.BottomPadding = 0;
            styl.Table.LeftPadding   = 0;
            styl.Table.RightPadding  = 0;
            //styl.Table.Borders.Enable = 1;
            qtable.Range.set_Style(styl);

            MSWord.Cell cell = qtable.Cell(1, 1);

            int headerwidth = 85;
            int levelwidth  = 100;

            object rows, cols;

            for (int i = 0; i < qdata.Length; i++)
            {
                int level = int.Parse(qdata[i][1]);
                if (level > 0)
                {
                    rows = 1;
                    cols = 2;
                    cell.Split(ref rows, ref cols);
                    cell.Range.Cells.SetWidth(level * levelwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                    cell = cell.Next;
                }

                rows = 1 + (string.IsNullOrWhiteSpace(qdata[i][0]) ? 0 : 1) + (string.IsNullOrWhiteSpace(qdata[i][6]) ? 0 : 1);
                cols = 2;
                cell.Split(ref rows, ref cols);
                cell.Merge(cell.Next);

                string title = String.Format("{0} {1} ({2})",
                                             qdata[i][2],
                                             (qdata[i][5].Length > 128 ? qdata[i][5].Remove(128) : qdata[i][5]).Replace("\n", "").Replace("\r", "").Replace("\t", ""),
                                             qdata[i][4]);

                cell.Range.Text      = title;
                cell.Range.Font.Bold = 1;
                cell.Range.set_Style(hstyles[level < 8 ? level:7]);
                cell = cell.Next;

                dlg.UpdateProgress("Exporting Work Item query to Microsoft Word document", "Adding to Word document " + qdata[i][3] + " #" + qdata[i][4], "status", progress++, 100, false, out bcanceled);
                if (progress == 100)
                {
                    progress = 0;
                }
                if (bcanceled)
                {
                    application.Visible = true;
                    Marshal.ReleaseComObject(document);
                    Marshal.ReleaseComObject(application);

                    return(true);
                }

                /*cell.Range.Text = "Title";
                 * cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                 * cell.Range.Font.Bold = 1;
                 * cell = cell.Next;
                 *
                 * cell.Range.Text = qdata[i][4];
                 * cell = cell.Next;*/

                /*cell.Range.Text = "Description";
                 * cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                 * cell.Range.Font.Bold = 1;
                 * cell = cell.Next;*/

                if (!string.IsNullOrWhiteSpace(qdata[i][6]))
                {
                    cell.Merge(cell.Next);
                    cell.Range.Text = qdata[i][6];
                    cell            = cell.Next;
                }

                if (!string.IsNullOrWhiteSpace(qdata[i][0]))
                {
                    cell.Range.Text = "Attachments";
                    cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                    cell.Range.Font.Bold = 1;
                    cell = cell.Next;

                    var query = qdata[i][0]
                                .Split(';')
                                .Where(x => !string.IsNullOrWhiteSpace(x))
                                .Select(x =>
                    {
                        string[] ch = x.Split('~');
                        return(new { name = ch[0], value = ch[1] });
                    }).ToArray();
                    cell.Split(query.Length, 1);

                    foreach (var kvp in query)
                    {
                        string localpath = Path.GetTempFileName() + "." + kvp.name;
                        //try { File.Delete(localpath); }
                        //catch { }

                        try
                        {
                            webclient.DownloadFile(kvp.value, localpath);
                        }
                        catch (Exception ex)
                        {
                            localpath = "";
                            Utilities.OutputCommandString(ex.ToString());
                        }

                        prg            = document.Paragraphs.Add();
                        prg.Range.Text = kvp.name;
                        prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleHeading3);

                        cell.Range.Text = kvp.name;
                        document.Hyperlinks.Add(cell.Range, missing, prg.Range);

                        prg.Range.InsertParagraphAfter();
                        document.InlineShapes.AddHorizontalLineStandard(prg.Range);
                        prg = document.Paragraphs.Add();

                        if (!string.IsNullOrEmpty(localpath))
                        {
                            try
                            {
                                Image img = Image.FromFile(localpath);
                                img.Dispose();
                                document.InlineShapes.AddPicture(localpath, false, true, prg.Range);
                            }
                            catch
                            {
                                if (Path.GetExtension(kvp.name).Equals(".sql", StringComparison.InvariantCultureIgnoreCase) ||
                                    Path.GetExtension(kvp.name).Equals(".txt", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    prg.Range.InsertFile(localpath);//, prg.Range, false, true, false);
                                }
                                else
                                {
                                    MSWord.InlineShape shape = document.InlineShapes.AddOLEObject(missing, localpath, false, false, missing, missing, missing, prg.Range);
                                    if (shape.OLEFormat.ClassType.ToString() != "Package")
                                    {
                                        shape.Width = document.PageSetup.PageWidth - 40;
                                    }
                                }
                            }
                        }
                        cell = cell.Next;
                    }
                    if (query.Length == 0)
                    {
                        cell = cell.Next;
                    }
                }
            }

            object styleTypePara = MSWord.WdStyleType.wdStyleTypeParagraph;

            MSWord.Style styl2 = document.Styles.Add("New Paragraph Style", ref styleTypePara);
            //styl2.ParagraphFormat.set_Style(MSWord.WdBuiltinStyle.wdStyleNormal);
            styl2.ParagraphFormat.LeftIndent      = 100;
            styl2.ParagraphFormat.RightIndent     = 100;
            styl2.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceSingle;
            styl2.ParagraphFormat.SpaceAfter      = 0;
            styl2.ParagraphFormat.SpaceBefore     = 0;

            MSWord.Paragraph       tocpara = document.Paragraphs[3];
            MSWord.TableOfContents tblct   = document.TablesOfContents.Add(tocpara.Range, missing, 1, 1);
            tblct.Update();
            //tblct.Range.set_Style(styl2);

            //application.Visible = true;

            Marshal.ReleaseComObject(document);
            Marshal.ReleaseComObject(application);

            return(false);
        }
Beispiel #15
0
        public void CreateProtocol(DateTimePicker dtp1, string txt1,
                                   string txt2, string txt3, string txt4, string txt5, string txt6,
                                   List <List <double> > list, ResistanceBox ResB, string Corresponds)
        {
            var wordApplication = new Word.Application();

            wordApplication.Visible = false;

            try
            {
                var wordDocument = wordApplication.Documents.Open(Application.StartupPath + @"\Program Files\Протокол.doc");

                ReplaceTextInDocument("{Протокол №:}", txt1, wordDocument);
                ReplaceTextInDocument("{Тип:}", txt2, wordDocument);
                ReplaceTextInDocument("{Номер:}", txt3, wordDocument);
                if (txt4.IndexOf('^') != -1)
                {
                    string degree;
                    string str = txt4;
                    int    FromIndex;
                    int    Len;
                    FromIndex = str.IndexOf('(') + 1;
                    Len       = str.IndexOf(')') - FromIndex;
                    degree    = str.Substring(FromIndex, Len);
                    str       = str.Remove(str.IndexOf('^'));
                    str       = str.Replace('*', '∙');
                    ReplaceTextInDocument("{Класс точности:}", str + degree, wordDocument);
                    Word.Range rng     = wordDocument.Content;
                    int        startIn = rng.Text.IndexOf(str) + str.Length;
                    rng.SetRange(startIn, startIn + degree.Length);
                    rng.Select();
                    rng.FormattedText.Font.Superscript = 1;
                }
                else
                {
                    ReplaceTextInDocument("{Класс точности:}", txt4, wordDocument);
                }


                ReplaceTextInDocument("{Предоставленный на поверку:}", txt5, wordDocument);
                ReplaceTextInDocument("{Дата поверки:}", dtp1.Value.ToLongDateString(), wordDocument);
                ReplaceTextInDocument("{Поверитель:}", txt6, wordDocument);

                ReplaceTextInDocument("{Протокол №:}", txt1, wordDocument);
                ReplaceTextInDocument("{Тип:}", txt2, wordDocument);
                ReplaceTextInDocument("{Номер:}", txt3, wordDocument);
                ReplaceTextInDocument("{не/соответствует}", Corresponds, wordDocument);


                Word.Table table = wordDocument.Tables[2];

                if ((ResB as ResistanceBox2) != null)
                {
                    InsertNullRes(table, list[0], 2);
                    InsertNullRes(table, list[1], 5);
                    list.RemoveAt(1);
                    list.RemoveAt(0);
                }
                else
                {
                    table.Rows[1].Delete();
                    table.Rows[3].Delete();
                    table.Rows[3].Delete();
                    table.Rows[3].Delete();
                    InsertNullRes(table, list[0], 1);
                    list.RemoveAt(0);
                }
                table.PreferredWidth = 560;
                Word.Table table3 = wordDocument.Tables[3];

                double DecadeValue = ResB.MinResistance;
                for (int i = 0; i < ResB.NumberDecade; i++)
                {
                    table3.Columns.Add();
                    table3.Cell(2, i + 2).Range.Text = "x " + DecadeValue.ToString();
                    DecadeValue *= 10;
                }

                for (int i = table3.Columns.Count; i > 2; i--)
                {
                    Word.Cell firstCell = table3.Cell(1, i);
                    Word.Cell currCell  = table3.Cell(1, i - 1);
                    if (currCell.ColumnIndex != firstCell.ColumnIndex)
                    {
                        firstCell.Merge(currCell);
                    }
                }

                table3.Cell(1, 1).Merge(table3.Cell(2, 1));
                table3.Cell(1, 1).Range.Text = "Номер ступени";
                table3.Cell(1, 2).Range.Text = "Действительное значение сопротивления, Ом";

                int maxCount = list[0].Count;
                foreach (var lis in list)
                {
                    if (lis.Count > maxCount)
                    {
                        maxCount = lis.Count;
                    }
                }

                for (int i = 0; i < maxCount; i++)
                {
                    table3.Rows.Add();
                    table3.Cell(i + 3, 1).Range.Text = (i + 1).ToString();
                }

                int rowIndex     = 0;
                int columnsIndex = 2;
                foreach (var item in list)
                {
                    foreach (var lis in item)
                    {
                        table3.Cell(rowIndex++ + 3, columnsIndex).Range.Text = lis.ToString();
                    }
                    columnsIndex++;
                    rowIndex = 0;
                }
                table3.PreferredWidth   = 560;
                wordApplication.Visible = true;
            }
            catch
            {
                MessageBox.Show("При создании документа возникла ошибка\nПроверьте наличие файла в папке шаблонов",
                                "При создании файла MS Word возникла ошибка.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                wordApplication.Quit();
            }
        }
Beispiel #16
0
        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            var t = e.Argument as Tuple <bool, bool, string, bool>;

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

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

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

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

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

            int columnsCount = 7;

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

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

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

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

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


            int rowCount  = 3;
            int rowNumber = 0;

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

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

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

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

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

            wdApp.Visible = true; //показать документ пользователю
        }
Beispiel #17
0
        public void Print()
        {
            Word.Application wdApp  = new Word.Application();
            Word.Document    wdDoc  = new Word.Document();
            Object           wdMiss = System.Reflection.Missing.Value;

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

            int columnsCount = 4;

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

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

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

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

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


            int rowCount  = 3;
            int rowNumber = 0;

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

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

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

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

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

            //wdApp.Visible = true; //показать документ пользователю
        }
        private void wizardOffertaEconomica_Finished(object sender, EventArgs e)
        {
            SetDocumentMargin();
            SetCustomStyle(document);

            //object noReset = false;
            //object password = "******";
            //object useIRM = false;
            //object enforceStyleLock = false;

            #region Logo Swen
            //Globals.ThisAddIn
            System.Drawing.Bitmap logoSwen1 = SwenBusinessTools.Properties.Resources.logoSwen;
            var temp     = Path.GetTempPath();
            var fileName = Path.Combine(temp, "logoSwen.png");
            logoSwen1.Save(fileName);

            var logoSwen  = document.InlineShapes.AddPicture(fileName, false, true);
            var logoShape = logoSwen.ConvertToShape();
            logoShape.Left                       = 0;
            logoShape.Top                        = 0;
            logoShape.TopRelative                = 0;
            logoShape.LeftRelative               = 0;
            logoShape.LockAspectRatio            = Office.MsoTriState.msoTrue;
            logoShape.Width                      = CentimetersToPoints(6.48f);
            logoShape.Height                     = CentimetersToPoints(3.66f);
            logoShape.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;
            logoShape.RelativeVerticalPosition   = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionMargin;
            #endregion


            object     start = 0, end = 0;
            Word.Range rng = document.Range(ref start, ref end);
            rng.SetRange(rng.End, rng.End);

            #region Tabella Tipo Documento
            Word.Table t0 = document.Tables.Add(document.Range(0, 0), 7, 9);
            t0.Range.set_Style("TabellaTipoDoc");
            t0.Range.Font.Size = 9;

            //imposta le colonne
            t0.Columns[1].Width = CentimetersToPoints(4.01f);

            //imposta le righe
            t0.Rows[1].HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
            t0.Rows[1].Height     = CentimetersToPoints(0.29f);
            t0.Rows[2].HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
            t0.Rows[2].Height     = CentimetersToPoints(1.22f);
            t0.Rows[3].HeightRule = Word.WdRowHeightRule.wdRowHeightExactly;
            t0.Rows[3].Height     = CentimetersToPoints(0.45f);
            t0.Rows[4].HeightRule = Word.WdRowHeightRule.wdRowHeightExactly;
            t0.Rows[4].Height     = CentimetersToPoints(0.45f);
            t0.Rows[5].HeightRule = Word.WdRowHeightRule.wdRowHeightExactly;
            t0.Rows[5].Height     = CentimetersToPoints(0.45f);
            t0.Rows[6].HeightRule = Word.WdRowHeightRule.wdRowHeightExactly;
            t0.Rows[6].Height     = CentimetersToPoints(0.45f);
            t0.Rows[7].HeightRule = Word.WdRowHeightRule.wdRowHeightExactly;
            t0.Rows[7].Height     = CentimetersToPoints(0.45f);


            t0.Cell(1, 2).Merge(t0.Cell(1, 7));
            t0.Cell(1, 3).Merge(t0.Cell(1, 4));
            t0.Cell(2, 1).Merge(t0.Cell(2, 9));
            t0.Cell(3, 2).Merge(t0.Cell(3, 9));
            t0.Cell(4, 2).Merge(t0.Cell(4, 9));
            t0.Cell(6, 2).Merge(t0.Cell(6, 9));
            t0.Cell(7, 2).Merge(t0.Cell(7, 9));

            t0.PreferredWidth                  = CentimetersToPoints(10.64f);
            t0.TableDirection                  = Word.WdTableDirection.wdTableDirectionLtr;
            t0.Rows.Alignment                  = Word.WdRowAlignment.wdAlignRowRight;
            t0.Rows.WrapAroundText             = -1;
            t0.Rows.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;
            t0.Rows.VerticalPosition           = CentimetersToPoints(1.3f);
            t0.Rows.RelativeVerticalPosition   = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
            t0.Rows.AllowOverlap               = -1;
            SetTableBolders(t0);

            t0.Cell(1, 1).Width = CentimetersToPoints(4.01f);
            t0.Cell(1, 2).Width = CentimetersToPoints(5.40f);
            t0.Cell(1, 3).Width = CentimetersToPoints(1.24f);
            t0.Cell(2, 1).Width = CentimetersToPoints(10.65f);
            t0.Cell(3, 1).Width = CentimetersToPoints(4.01f);
            t0.Cell(3, 2).Width = CentimetersToPoints(6.64f);
            t0.Cell(4, 1).Width = CentimetersToPoints(4.01f);
            t0.Cell(4, 2).Width = CentimetersToPoints(6.64f);
            t0.Cell(6, 1).Width = CentimetersToPoints(4.01f);
            t0.Cell(6, 2).Width = CentimetersToPoints(6.64f);
            t0.Cell(7, 1).Width = CentimetersToPoints(4.01f);
            t0.Cell(7, 2).Width = CentimetersToPoints(6.64f);
            t0.Cell(5, 1).Width = CentimetersToPoints(4.01f);
            t0.Cell(5, 2).Width = CentimetersToPoints(0.83f);
            t0.Cell(5, 3).Width = CentimetersToPoints(0.83f);
            t0.Cell(5, 4).Width = CentimetersToPoints(0.83f);
            t0.Cell(5, 5).Width = CentimetersToPoints(0.83f);
            t0.Cell(5, 6).Width = CentimetersToPoints(0.83f);
            t0.Cell(5, 7).Width = CentimetersToPoints(0.83f);
            t0.Cell(5, 8).Width = CentimetersToPoints(0.83f);
            t0.Cell(5, 9).Width = CentimetersToPoints(0.83f);

            t0.Cell(1, 1).Shading.Texture = Word.WdTextureIndex.wdTextureNone;
            t0.Cell(1, 1).Shading.BackgroundPatternColor = (Word.WdColor)(219 + 0x100 * 229 + 0x10000 * 241);
            t0.Cell(1, 2).Shading.Texture = Word.WdTextureIndex.wdTextureNone;
            t0.Cell(1, 2).Shading.BackgroundPatternColor = (Word.WdColor)(219 + 0x100 * 229 + 0x10000 * 241);
            t0.Cell(1, 3).Shading.Texture = Word.WdTextureIndex.wdTextureNone;
            t0.Cell(1, 3).Shading.BackgroundPatternColor = (Word.WdColor)(219 + 0x100 * 229 + 0x10000 * 241);
            t0.Cell(3, 1).Shading.Texture = Word.WdTextureIndex.wdTextureNone;
            t0.Cell(3, 1).Shading.BackgroundPatternColor = (Word.WdColor)(219 + 0x100 * 229 + 0x10000 * 241);
            t0.Cell(4, 1).Shading.Texture = Word.WdTextureIndex.wdTextureNone;
            t0.Cell(4, 1).Shading.BackgroundPatternColor = (Word.WdColor)(219 + 0x100 * 229 + 0x10000 * 241);
            t0.Cell(5, 1).Shading.Texture = Word.WdTextureIndex.wdTextureNone;
            t0.Cell(5, 1).Shading.BackgroundPatternColor = (Word.WdColor)(219 + 0x100 * 229 + 0x10000 * 241);
            t0.Cell(6, 1).Shading.Texture = Word.WdTextureIndex.wdTextureNone;
            t0.Cell(6, 1).Shading.BackgroundPatternColor = (Word.WdColor)(219 + 0x100 * 229 + 0x10000 * 241);
            t0.Cell(7, 1).Shading.Texture = Word.WdTextureIndex.wdTextureNone;
            t0.Cell(7, 1).Shading.BackgroundPatternColor = (Word.WdColor)(219 + 0x100 * 229 + 0x10000 * 241);

            t0.Cell(1, 1).Range.Text        = "Tipo documento";
            t0.Cell(1, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(1, 1).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(1, 1).Range.ParagraphFormat.SpaceBefore = 0;
            t0.Cell(1, 2).Range.Text        = "Offerta Economica";
            t0.Cell(1, 2).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(1, 2).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(1, 2).Range.ParagraphFormat.SpaceBefore = 0;
            t0.Cell(1, 3).Range.Text        = "OFC";
            t0.Cell(1, 3).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(1, 3).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(1, 3).Range.ParagraphFormat.SpaceBefore = 0;


            t0.Cell(2, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(2, 1).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(2, 1).Range.ParagraphFormat.SpaceBefore = 0;
            rng.SetRange(t0.Cell(2, 1).Range.Start, t0.Cell(2, 1).Range.Start);
            t0.Cell(2, 1).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "FILENAME  \\*Upper ", true);

            t0.Cell(3, 1).Range.Text        = "Data";
            t0.Cell(3, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(3, 1).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(3, 1).Range.ParagraphFormat.SpaceBefore = 0;

            t0.Cell(3, 2).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(3, 2).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(3, 2).Range.ParagraphFormat.SpaceBefore = 0;
            rng.SetRange(t0.Cell(3, 2).Range.Start, t0.Cell(3, 2).Range.Start);
            t0.Cell(3, 2).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "FILENAME  \\*Upper ", true);


            t0.Cell(4, 1).Range.Text        = "Invio per";
            t0.Cell(4, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(4, 1).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(4, 1).Range.ParagraphFormat.SpaceBefore = 0;

            t0.Cell(4, 2).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(4, 2).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(4, 2).Range.ParagraphFormat.SpaceBefore = 0;
            rng.SetRange(t0.Cell(4, 2).Range.Start, t0.Cell(4, 2).Range.Start);
            t0.Cell(4, 2).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "FILENAME  \\*Upper ", true);


            t0.Cell(5, 1).Range.Text        = "Classificazione";
            t0.Cell(5, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(5, 1).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(5, 1).Range.ParagraphFormat.SpaceBefore = 0;
            t0.Cell(5, 2).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

            t0.Cell(6, 1).Range.Text        = "Versione";
            t0.Cell(6, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(6, 1).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(6, 1).Range.ParagraphFormat.SpaceBefore = 0;
            t0.Cell(6, 2).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(6, 2).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(6, 2).Range.ParagraphFormat.SpaceBefore = 0;
            rng.SetRange(t0.Cell(6, 2).Range.Start, t0.Cell(6, 2).Range.Start);
            t0.Cell(6, 2).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "FILENAME  \\*Upper ", true);


            t0.Cell(7, 1).Range.Text        = "Id documento";
            t0.Cell(7, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(7, 1).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(7, 1).Range.ParagraphFormat.SpaceBefore = 0;

            t0.Cell(7, 2).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t0.Cell(7, 2).Range.ParagraphFormat.SpaceAfter  = 0;
            t0.Cell(7, 2).Range.ParagraphFormat.SpaceBefore = 0;
            rng.SetRange(t0.Cell(7, 2).Range.Start, t0.Cell(7, 2).Range.Start);
            t0.Cell(7, 2).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "FILENAME  \\*Upper ", true);

            #endregion

            rng.SetRange(t0.Range.End, t0.Range.End);
            rng.InsertParagraphAfter();
            rng.InsertParagraphAfter();
            rng.InsertParagraphAfter();
            rng.InsertParagraphAfter();
            rng.InsertParagraphAfter();
            rng.InsertParagraphAfter();
            rng.SetRange(rng.End, rng.End);


            #region Tabella riferimenti
            Word.Table t1 = document.Tables.Add(rng, 8, 3);
            t1.Range.set_Style("TabellaFirma");
            t1.Range.Font.Size = 9;

            t1.PreferredWidth                  = CentimetersToPoints(17.5f);
            t1.TableDirection                  = Word.WdTableDirection.wdTableDirectionLtr;
            t1.Rows.Alignment                  = Word.WdRowAlignment.wdAlignRowCenter;
            t1.Rows.WrapAroundText             = -1;
            t1.Rows.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;
            t1.Rows.VerticalPosition           = CentimetersToPoints(5.6f);
            t1.Rows.RelativeVerticalPosition   = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
            t1.Rows.AllowOverlap               = -1;

            t1.Columns[1].Width = CentimetersToPoints(7.64f);
            t1.Columns[2].Width = CentimetersToPoints(1.15f);
            t1.Columns[3].Width = CentimetersToPoints(8.72f);

            foreach (var row in t1.Rows)
            {
                ((Word.Row)row).HeightRule = Word.WdRowHeightRule.wdRowHeightExactly;
                ((Word.Row)row).Height     = CentimetersToPoints(0.4f);
            }

            t1.Cell(1, 1).Range.InsertAfter("Rif. Vs. richiesta ");
            rng.SetRange(t1.Cell(1, 1).Range.Start + "Rif. Vs. richiesta ".Length, t1.Cell(1, 1).Range.Start + "Rif. Vs. richiesta ".Length);
            t1.Cell(1, 1).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "FILENAME  \\*Upper ", true);

            t1.Cell(2, 1).Range.Text = "Vs. prot. N° ";
            rng.SetRange(t1.Cell(2, 1).Range.Start + "Vs. prot. N° ".Length, t1.Cell(2, 1).Range.Start + "Vs. prot. N° ".Length);
            t1.Cell(2, 1).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "FILENAME  \\*Upper ", true);

            t1.Cell(3, 1).Range.Text = "Del ";
            rng.SetRange(t1.Cell(3, 1).Range.Start + "Del ".Length, t1.Cell(3, 1).Range.Start + "Del ".Length);
            t1.Cell(3, 1).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "FILENAME  \\*Upper ", true);

            document.Range(t1.Cell(1, 1).Range.Start, t1.Cell(3, 1).Range.End).Select();
            Selection.Range.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            Selection.Range.Borders.OutsideColor     = (Word.WdColor)(51 + 0x100 * 51 + 0x10000 * 153);

            t1.Cell(4, 1).Range.Text = "Rif. Ns. Off. Tecnica ";
            rng.SetRange(t1.Cell(4, 1).Range.Start + "Rif. Ns. Off. Tecnica ".Length, t1.Cell(4, 1).Range.Start + "Rif. Ns. Off. Tecnica ".Length);
            t1.Cell(4, 1).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "FILENAME  \\*Upper ", true);

            t1.Cell(5, 1).Range.Text = "Ns. protocollo N° ";
            rng.SetRange(t1.Cell(5, 1).Range.Start + "Ns. protocollo N° ".Length, t1.Cell(5, 1).Range.Start + "Ns. protocollo N° ".Length);
            t1.Cell(5, 1).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "FILENAME  \\*Upper ", true);

            t1.Cell(6, 1).Range.Text = "Del ";
            rng.SetRange(t1.Cell(6, 1).Range.Start + "Del ".Length, t1.Cell(6, 1).Range.Start + "Del ".Length);
            t1.Cell(6, 1).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "AUTHOR  \\*Upper ", true);


            document.Range(t1.Cell(4, 1).Range.Start, t1.Cell(6, 1).Range.End).Select();
            Selection.Range.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            Selection.Range.Borders.OutsideColor     = (Word.WdColor)(51 + 0x100 * 51 + 0x10000 * 153);

            t1.Cell(7, 1).Range.Text = "Rif. Persona ";
            rng.SetRange(t1.Cell(6, 1).Range.Start + "Del ".Length, t1.Cell(6, 1).Range.Start + "Del ".Length);
            t1.Cell(6, 1).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "AUTHOR  \\*Upper ", true);

            t1.Cell(8, 1).Range.Text = "Progetto ";
            rng.SetRange(t1.Cell(6, 1).Range.Start + "Del ".Length, t1.Cell(6, 1).Range.Start + "Del ".Length);
            t1.Cell(8, 1).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "AUTHOR  \\*Upper ", true);

            document.Range(t1.Cell(7, 1).Range.Start, t1.Cell(8, 1).Range.End).Select();
            Selection.Range.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            Selection.Range.Borders.OutsideColor     = (Word.WdColor)(51 + 0x100 * 51 + 0x10000 * 153);

            t1.Cell(1, 3).Range.Text = "Destinatario ";
            t1.Cell(2, 3).Range.Text = "Spett. ";
            t1.Cell(3, 3).Range.Text = "";
            t1.Cell(4, 3).Range.Text = "";
            t1.Cell(5, 3).Range.Text = "";
            t1.Cell(6, 3).Range.Text = "";
            document.Range(t1.Cell(1, 3).Range.Start, t1.Cell(6, 3).Range.End).Select();
            Selection.Range.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            Selection.Range.Borders.OutsideColor     = (Word.WdColor)(51 + 0x100 * 51 + 0x10000 * 153);

            t1.Cell(7, 3).Range.Text = "C.A.";
            t1.Cell(8, 3).Range.Text = "P.C.";
            document.Range(t1.Cell(7, 3).Range.Start, t1.Cell(8, 3).Range.End).Select();
            Selection.Range.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            Selection.Range.Borders.OutsideColor     = (Word.WdColor)(51 + 0x100 * 51 + 0x10000 * 153);
            #endregion

            rng.SetRange(t1.Range.End, t1.Range.End);
            rng.SetRange(rng.End, rng.End);

            Word.Paragraph p1 = document.Paragraphs.Add(rng);
            p1.Range.Text = "Con la presente Vi rimettiamo offerta economica per i prodotti / servizi elencati nella sezione “Configurazione offerta”, eventualmente descritti dettagliatamente nell’apposita offerta tecnica indicata in calce.";
            p1.Range.set_Style("normale");
            p1.Range.InsertParagraphAfter();

            #region Note
            //Word.Paragraph notaTecnica = document.Paragraphs.Add(System.Reflection.Missing.Value);
            Word.Paragraph notaTecnica = document.Paragraphs.Add(p1.Range);
            notaTecnica.Range.Text = "Nota tecnica";
            notaTecnica.Range.set_Style("titolo 3");
            notaTecnica.Range.InsertParagraphAfter();

            Word.Paragraph testoNotaTecnica = document.Paragraphs.Add(notaTecnica.Range);
            testoNotaTecnica.Range.Text = txtNotatecnica.Text;
            testoNotaTecnica.Range.set_Style("normale");
            testoNotaTecnica.Range.InsertParagraphAfter();

            Word.Paragraph notaCommerciale = document.Paragraphs.Add(testoNotaTecnica.Range);
            notaCommerciale.Range.Text = "Nota commerciale";
            notaCommerciale.Range.set_Style("titolo 3");
            notaCommerciale.Range.InsertParagraphAfter();

            Word.Paragraph testoNotaCommerciale = document.Paragraphs.Add(notaCommerciale.Range);
            testoNotaCommerciale.Range.Text = txtNotaCommerciale.Text;
            testoNotaCommerciale.Range.set_Style("normale");
            testoNotaCommerciale.Range.InsertParagraphAfter();
            #endregion

            #region Condizioni Speciali

            #endregion

            #region Condizioni Generali
            Word.Paragraph condizioniGenerali = document.Paragraphs.Add(testoNotaCommerciale.Range);
            condizioniGenerali.Range.Text = "Condizioni generali";
            condizioniGenerali.Range.set_Style("titolo 3");
            condizioniGenerali.Range.InsertParagraphAfter();

            Word.Paragraph testoCondizioniGenerali = document.Paragraphs.Add(condizioniGenerali.Range);
            testoCondizioniGenerali.Range.Text = "La presente offerta si intende valida per 7 gg. alle seguenti condizioni di fornitura (individuare le voci che interessano sulla base della categoria indicata per ciascun articolo in offerta); l’accettazione della presente offerta implica la tacita accettazione di tutte le condizioni applicabili a ciascuna categoria merceologica offerta.";
            testoCondizioniGenerali.Range.set_Style("normale");
            testoCondizioniGenerali.Range.InsertParagraphAfter();

            Word.Paragraph testoGenerali = document.Paragraphs.Add(testoCondizioniGenerali.Range);
            testoGenerali.Range.Text = "Generali:";
            testoGenerali.Range.set_Style("condizionigenerali");
            testoGenerali.Range.InsertParagraphAfter();

            Word.Paragraph testoElencoGenerale = document.Paragraphs.Add(testoGenerali.Range);
            testoElencoGenerale.Range.ListFormat.ApplyBulletDefault();

            testoElencoGenerale.Range.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphJustify;
            testoElencoGenerale.Range.ParagraphFormat.OutlineLevel    = Word.WdOutlineLevel.wdOutlineLevelBodyText;
            testoElencoGenerale.Range.ParagraphFormat.SpaceAfterAuto  = 0;
            testoElencoGenerale.Range.ParagraphFormat.SpaceBeforeAuto = 0;
            testoElencoGenerale.Range.ParagraphFormat.FirstLineIndent = -7f;
            testoElencoGenerale.Range.ParagraphFormat.LeftIndent      = 7f;
            testoElencoGenerale.Range.ParagraphFormat.SpaceAfter      = 0F;
            testoElencoGenerale.Range.ParagraphFormat.SpaceBefore     = 0F;
            testoElencoGenerale.Range.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceMultiple;
            testoElencoGenerale.Range.ParagraphFormat.LineSpacing     = 13.8f;
            testoElencoGenerale.Range.Font.Bold  = 0;
            testoElencoGenerale.Range.Font.Color = Word.WdColor.wdColorBlack;

            testoElencoGenerale.Range.InsertBefore("I prezzi sono da considerarsi al netto dell'IVA \n");
            testoElencoGenerale.Range.InsertBefore("Il pagamento non potrà comunque essere differito oltre i limiti indicati in fattura a qualunque titolo, incluse eventuali contestazioni o malfunzionamenti anche parziali sia su prodotti Swen o di terzi, (che vanno comunque disciplinati come \"interventi in garanzia\", da espletarsi come specificato nel seguito) che sui servizi resi da Swen, per i quali valgono le penali stabilite nei SLA concordati con il Cliente \n");
            testoElencoGenerale.Range.InsertBefore("Il mancato o ritardato pagamento delle fatture emesse a qualunque titolo nei confronti di un Cliente comporta l’immediata sospensione di servizi e forniture servizio fino a regolarizzazione, fatti salvi eventuali interessi, risarcimenti e danni subiti.\n");
            testoElencoGenerale.Range.InsertBefore("Eventuali supplementi richiesti dal Cliente (diversi da  quanto specificato nella presente offerta) devono essere comunque disciplinati in separata sede\n");
            testoElencoGenerale.Range.InsertBefore("La consegna di tutti i beni elencati e comunque il completamento della fornitura è subordinato alla permanenza di disponibilità commerciale dei prodotti offerti. In caso di documentata indisponibilità sul mercato nei tempi stabiliti per la consegna, la SWEN si riserva il diritto di escludere alcuni degli articoli offerti dalla fornitura senza alcuna penale (se non la restituzione di eventuali acconti già versati in proporzione al valore degli articoli non disponibili); qualora l’indisponibilità sia temporanea il Cliente potrà scegliere se attendere la nuova disponibilità o rinunciare agli articoli non disponibili; in caso si indisponibilità permanente è implicita la rinuncia del Cliente\n");
            testoElencoGenerale.Range.InsertBefore("In presenza di articoli indisponibili, la SWEN si impegna a fornire prodotti alternativi di pari requisiti con offerta separata, a prezzi e condizioni da rinegoziare\n");
            testoElencoGenerale.Range.InsertBefore("I beni materiali sono coperti da garanzie a norma di legge ed in particolare:\n");
            testoElencoGenerale.Range.ListFormat.ListIndent();
            testoElencoGenerale.Range.InsertBefore("per i consumatori, cioè coloro che acquistano per scopi estranei alla propria attività professionale o imprenditoriale, il venditore applicherà il Decreto Legislativo 2 febbraio 2002, n.24. - artt. 1519-bis e seguenti c.c. - (due anni dalla consegna alle condizioni di legge); \n");
            testoElencoGenerale.Range.InsertBefore("per gli altri acquirenti, che solitamente acquistano con partita IVA, varranno le garanzie di legge di cui agli articoli 1490 e seguenti c.c. (un anno dalla consegna alle condizioni di legge). \n");
            testoElencoGenerale.Range.InsertBefore("Restano in ogni caso fatte salve eventuali deroghe specifiche per prodotto o categoria di prodotti (come di seguito indicato) e le garanzie contrattuali rilasciate direttamente dal produttore.");

            Word.Paragraph w1 = document.Paragraphs.Add(testoElencoGenerale.Range);
            w1.Range.Text = "\n";
            w1.Range.InsertParagraphAfter();
            #endregion

            Word.Table table = document.Tables.Add(testoNotaCommerciale.Range, 5, 2);
            SetTableBolders(table);
            table.Range.set_Style("TabellaFirma");

            table.Rows[1].Height = CentimetersToPoints(0.93f);
            table.Rows[2].Height = CentimetersToPoints(1.25f);
            table.Rows[3].Height = CentimetersToPoints(1.24f);
            table.Rows[4].Height = CentimetersToPoints(1.86f);
            table.Rows[5].Height = CentimetersToPoints(1.86f);

            //first row
            Word.Cell cellOrdineAcquisto = table.Cell(1, 1);
            cellOrdineAcquisto.Range.Text       = "Ordine di acquisto";
            cellOrdineAcquisto.Range.Font.Bold  = 1;
            cellOrdineAcquisto.Range.Font.Size  = 13.0f;
            cellOrdineAcquisto.Range.Font.Color = (Word.WdColor)(128 + 0x100 * 128 + 0x10000 * 128);

            Word.Cell cellRiferimento = table.Cell(1, 2);
            cellRiferimento.Range.Text = "Riferimento (sarà citato in fattura)";

            //2° row
            Word.Cell cellRrdianante = table.Cell(2, 1);
            cellRrdianante.Range.Text = "Ordinante (si prega specificare il nome e cognome del responsabile per l’ordine)";

            Word.Cell cellDataApprovazione = table.Cell(2, 2);
            cellDataApprovazione.Range.Text = "Data approvazione";

            //3° row
            Word.Cell cellOpzioniScelte = table.Cell(3, 1);
            cellOpzioniScelte.Range.Text = "Opzioni scelte (indicare lista dei riferimenti in caso di opzioni o alternative)";

            Word.Cell cellImportoTotale = table.Cell(3, 2);
            cellImportoTotale.Range.Text = "IMPORTO TOTALE escl. IVA (incluse opzioni desiderate))";

            //4° row
            Word.Cell firmaClienteAccettazione = table.Cell(4, 1);
            firmaClienteAccettazione.Merge(table.Cell(4, 2));
            firmaClienteAccettazione.Range.Text = "Firma del Cliente per accettazione della presente offerta quale ordine di acquisto";

            //5° row
            Word.Cell firmaCliente = table.Cell(5, 1);
            firmaCliente.Merge(table.Cell(5, 2));
            firmaCliente.Range.Text = "Firma del Cliente ai sensi degli art. 1341 e 1342 del Codice Civile e successive modificazioni, per approvazione esplicita di tutti i paragrafi della presente offerta, in particolare ogni singolo comma del paragrafo “condizioni generali”. ";

            //document.Protect(Word.WdProtectionType.wdAllowOnlyReading, ref noReset, ref password, ref useIRM, ref enforceStyleLock);

            //notaTecnica.Range.Editors.Add(Word.WdEditorType.wdEditorEveryone);



            #region FOOTER
            //Aggiungi footer
            var footer = document.Sections[1].Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];

            var footerRng = ((Word.HeaderFooter)footer).Range;

            Word.Table t2 = footerRng.Tables.Add(footerRng, 2, 4);
            SetTableBolders(t2);
            t2.Range.set_Style("TabellaFirma");
            t2.Range.Font.Bold = 0;
            t2.Rows.Alignment  = Word.WdRowAlignment.wdAlignRowCenter;


            t2.PreferredWidth                  = CentimetersToPoints(17.46f);
            t2.TableDirection                  = Word.WdTableDirection.wdTableDirectionLtr;
            t2.Rows.WrapAroundText             = -1;
            t2.Rows.AllowOverlap               = -1;
            t2.Rows.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionColumn;
            t2.Rows.VerticalPosition           = CentimetersToPoints(27f);
            t2.Rows.RelativeVerticalPosition   = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;

            SetTableBolders(t2, (Word.WdColor)(51 + 0x100 * 51 + 0x10000 * 153));

            //imposta merge delle celle
            t2.Cell(1, 1).Merge(t2.Cell(2, 1));
            t2.Cell(1, 2).Merge(t2.Cell(2, 2));
            t2.Cell(1, 2).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            t2.Cell(1, 3).Merge(t2.Cell(2, 3));
            t2.Cell(1, 1).Width = CentimetersToPoints(2.54f);
            t2.Cell(1, 2).Width = CentimetersToPoints(6.35f);
            t2.Cell(1, 3).Width = CentimetersToPoints(6.03f);
            t2.Cell(1, 4).Width = CentimetersToPoints(2.54f);
            t2.Cell(2, 4).Width = CentimetersToPoints(2.54f);


            System.Drawing.Bitmap logoSwen2 = SwenBusinessTools.Properties.Resources.logoSwenSmall;
            fileName = Path.Combine(temp, "logoSewnSmall.jpeg");
            logoSwen2.Save(fileName);

            var logoSwenSmall = document.InlineShapes.AddPicture(fileName, false, true);
            logoSwenSmall.Width           = CentimetersToPoints(2.24f);
            logoSwenSmall.Height          = CentimetersToPoints(1.24f);
            logoSwenSmall.LockAspectRatio = Office.MsoTriState.msoTrue;

            logoSwenSmall.Range.Cut();
            t2.Cell(1, 1).Range.PasteAndFormat(Word.WdRecoveryType.wdFormatOriginalFormatting);
            Clipboard.Clear();

            t2.Cell(1, 2).Range.Font.Size  = 6;
            t2.Cell(1, 2).Range.Font.Name  = "Trebuchet MS";
            t2.Cell(1, 2).Range.Font.Color = ColorRGB(54, 95, 145);
            t2.Cell(1, 2).Range.ParagraphFormat.SpaceAfter  = 0;
            t2.Cell(1, 2).Range.ParagraphFormat.SpaceBefore = 0;
            t2.Cell(1, 2).Range.ParagraphFormat.Alignment   = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            t2.Cell(1, 2).VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

            t2.Cell(1, 2).Range.InsertAfter("SWEN SRL - VIA FOIANO DELLA CHIANA, 27 - 000147 ROMA\n");
            t2.Cell(1, 2).Range.InsertAfter("TEL 06-45664422 - FAX 06-4523116\n");
            t2.Cell(1, 2).Range.InsertAfter("SEDE LEGALE: VIA FOAIANO DELLA CHIANA, 27 - 00146 ROMA\n");
            t2.Cell(1, 2).Range.InsertAfter("P.IVA 03553421003 - TRIB. DI ROMA N. 2060/89 - CCIAA 672853\n");
            t2.Cell(1, 2).Range.InsertAfter("HTTP://WWW.SWEN.IT - E-MAIL: [email protected]");

            t2.Cell(1, 4).Range.InsertAfter("Pag ");
            rng.SetRange(t2.Cell(1, 4).Range.Start + "Pag ".Length, t2.Cell(1, 4).Range.Start + "Pag ".Length);
            t2.Cell(1, 4).Range.Fields.Add(rng, Word.WdFieldType.wdFieldEmpty, "FILENAME  \\*Upper ", true);

            #endregion

            document.SaveAs2("c:\\temp\\pippo.docx");
            document.Activate();
        }
Beispiel #19
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var t = e.Argument as Tuple <string, string, string>;

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

            DataSet ds1 = new DataSet();

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

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

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

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

            int columnsCount = 6;

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

            tb.Rows[2].Height = 30;

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

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

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

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

            int rowCount  = 3;
            int rowNumber = 0;

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

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

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


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

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

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

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

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

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

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

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

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

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

            string select = @"SELECT Student.name";

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

            DataSet ds1 = new DataSet();

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

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

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

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

            int columnsCount = 0;

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

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

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

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

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

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

            int rowCount  = 2;
            int rowNumber = 0;

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

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


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

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

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

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

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