private void button1_Click(object sender, EventArgs e) { object oMissing = System.Reflection.Missing.Value; Word.Application oWord = new Word.Application(); oWord.Visible = true; Word.Documents oDocs = oWord.Documents; object oFile = "f:\\Andre.doc"; /*Word.Document oDoc = oDocs.Open("f:\\Andre.doc", ref oMissing, * ref oMissing, ref oMissing, ref oMissing, ref oMissing, * ref oMissing, ref oMissing, ref oMissing, ref oMissing, * ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); */ var oDoc = oWord.Documents.Open("f:\\Andre.docx"); oWord.Run("Sort"); oDoc.Close(ref oMissing, ref oMissing, ref oMissing); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oDoc); oDoc = null; System.Runtime.InteropServices.Marshal.ReleaseComObject(oDocs); oDocs = null; oWord.Quit(ref oMissing, ref oMissing, ref oMissing); System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord); oWord = null; GC.Collect(); }
void runMacroInWord(string filePath, string macroName, string parameter) { Word.Application word = new Word.Application(); Word.Document doc = new Word.Document(); doc = word.Documents.Open(filePath); word.Run(macroName, parameter); doc.Save(); doc.Close(); word.Quit(); Process.Start(filePath); }
private void button2_Click(object sender, EventArgs e) { InitializeComponent(); OpenFileDialog OPF = new OpenFileDialog(); OPF.Filter = "Файлы docx|*.docx"; object oFile; if (OPF.ShowDialog() == DialogResult.OK) { oFile = (OPF.FileName); } else { oFile = "f:\\Andre.docx"; } object oMissing = System.Reflection.Missing.Value; Word.Application oWord = new Word.Application(); oWord.Visible = true; Word.Documents oDocs = oWord.Documents; var oDoc = oWord.Documents.Open(oFile); oWord.Run("Sort"); oDoc.Close(ref oMissing, ref oMissing, ref oMissing); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oDoc); oDoc = null; System.Runtime.InteropServices.Marshal.ReleaseComObject(oDocs); oDocs = null; oWord.Quit(ref oMissing, ref oMissing, ref oMissing); System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord); oWord = null; GC.Collect(); }
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; //показать документ пользователю }
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; //показать документ пользователю }
private void printToWord(bool bPreview) { object strFile; Microsoft.Office.Interop.Word.Application objWord = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document objDoc = new Microsoft.Office.Interop.Word.Document(); object missing = System.Reflection.Missing.Value; object myTrue = true; object myFalse = false; objWord.Options.MapPaperSize = false; object objBookmark = "ContractOID"; clsGlobalVariable objGlobal = new clsGlobalVariable(); TreeNode objWordNode = trDocuments.Nodes[0]; foreach (TreeNode objNode in objWordNode.Nodes) { if (objNode.Checked == true) { strFile = objNode.Text; objDoc = objWord.Documents.AddOld(ref strFile, ref missing); try { objBookmark = "ContractOID"; objDoc.FormFields.get_Item(ref objBookmark).Result = objContact.ContractOID.ToString(); string sqlserver = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\ODBC\\ODBC.INI\\" + objGlobal.DMSDBName, "Server", "localhost"); objBookmark = "VSPISRV"; objDoc.FormFields.get_Item(ref objBookmark).Result = sqlserver; objBookmark = "VSPIDB"; objDoc.FormFields.get_Item(ref objBookmark).Result = objGlobal.DMSDBName; objBookmark = "VSPIUSER"; objDoc.FormFields.get_Item(ref objBookmark).Result = objGlobal.DMSUserName; objBookmark = "VSPIPASS"; objDoc.FormFields.get_Item(ref objBookmark).Result = objGlobal.DMSDBPass; objWord.Run("GetExtraData"); } catch (Exception ex) { _log.Error(ex.ToString()); } if (!bPreview) { objDoc.PrintOutOld(ref myFalse, ref myFalse, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); objDoc.Close(ref myFalse, ref missing, ref missing); } else { objDoc.Activate(); objWord.Visible = true; } } } if (!bPreview) { objWord.Quit(ref myFalse, ref missing, ref missing); objWord = null; } }
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; //показать документ пользователю }
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 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; //показать документ пользователю }
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; //показать документ пользователю }
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; //показать документ пользователю }
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; //показать документ пользователю }