private void PrintTerminos(ObservableCollection <Terminos> terminosPrint) { foreach (Terminos termino in terminosPrint) { if (!String.IsNullOrEmpty(termino.Definicion)) { Microsoft.Office.Interop.Word.Paragraph par = oDoc.Content.Paragraphs.Add(ref oMissing); par.Range.Font.Bold = 1; par.Range.Font.Size = 14; par.Range.Font.Name = "Arial"; par.Range.Text = termino.Termino; par.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify; par.Range.InsertParagraphAfter(); par.Range.Text = termino.Definicion; par.Range.Font.Bold = 0; par.Range.Font.Size = 12; par.Range.InsertParagraphAfter(); par.Range.InsertParagraphAfter(); par.Range.Font.Bold = 0; par.Range.InsertParagraphAfter(); } } }
private void ProcessHeaderFooter(Microsoft.Office.Interop.Word.Application wApp, Microsoft.Office.Interop.Word.Document wDoc) { // copy header wApp.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView; wApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader; Microsoft.Office.Interop.Word.Range wHeaderRange = wApp.Selection.HeaderFooter.Range; ProcessBookmarks(wHeaderRange.Bookmarks, wDoc); wHeaderRange.CopyAsPicture(); // paste header wApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; wApp.Selection.HomeKey(Microsoft.Office.Interop.Word.WdUnits.wdStory); Microsoft.Office.Interop.Word.Paragraph wHeader = wDoc.Content.Paragraphs.Add(); wApp.Selection.PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdPasteDefault); // copy footer wApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter; Microsoft.Office.Interop.Word.Range wFooterRange = wApp.Selection.HeaderFooter.Range; ProcessBookmarks(wFooterRange.Bookmarks, wDoc); wFooterRange.CopyAsPicture(); // paste footer wApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; wApp.Selection.EndKey(Microsoft.Office.Interop.Word.WdUnits.wdStory); Microsoft.Office.Interop.Word.Paragraph wFooter = wDoc.Content.Paragraphs.Add(); wApp.Selection.PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdPasteDefault); }
public void GeneraDocumentoWord() { oWord = new Microsoft.Office.Interop.Word.Application(); oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); foreach (string letra in letrasImprimir) { Microsoft.Office.Interop.Word.Paragraph titulo = oDoc.Content.Paragraphs.Add(ref oMissing); titulo.Range.Font.Bold = 1; titulo.Range.Font.Size = 72; titulo.Range.Font.Name = "Algerian"; titulo.Range.Text = letra; titulo.Range.InsertParagraphAfter(); ObservableCollection <Terminos> voces = (from n in TerminosSingleton.Terminos where n.TerminoStr.StartsWith(letra) orderby n.TerminoStr select n).ToObservableCollection(); this.PrintTerminos(voces); oDoc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak); } oWord.Visible = true; }
private void createWords() { int filesToCreateTemp = frm1.filesToCreate; // avoid change in '#files to be created' during runtime try { string workingDir = frm1.workingDirectory + "officeSimulation_word\\"; System.IO.Directory.CreateDirectory(workingDir); int documentCount = 0; string wordFileNameDate = frm1.wordFileName + DateTime.Now.ToString("dd-MM-yyyy_HH-mm"); string wordFileNameDateFinal; // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Word instance ~~~~~~~~~~~~~~~~~~~~~~~~~ var winword = new Microsoft.Office.Interop.Word.Application(); winword.ShowAnimation = false; winword.Visible = false; object winWordMissing = System.Reflection.Missing.Value; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ while (documentCount < filesToCreateTemp) { wordFileNameDateFinal = wordFileNameDate + "_" + documentCount; // ~~~~~~ create word files (vary formatting) try { if (frm1.varyFormatting) { //Selecting random lorem text length Random r = new Random(DateTime.Now.Millisecond); int rLorem1 = r.Next(0, 5); int rLorem2 = r.Next(0, 5); int rLorem3 = r.Next(0, 5); int rLorem4 = r.Next(0, 2); int rLorem5 = r.Next(0, 2); //Create a new document Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref winWordMissing, ref winWordMissing, ref winWordMissing, ref winWordMissing); //Add header into the document foreach (Microsoft.Office.Interop.Word.Section section in document.Sections) { //Get the header range and add the header details. Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue; headerRange.Font.Size = 10; headerRange.Text = frm1.lorems[rLorem4]; } //Add the footers into the document foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections) { //Get the footer range and add the footer details. Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed; footerRange.Font.Size = 10; footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; footerRange.Text = frm1.lorems[rLorem5]; } //adding text to document document.Content.SetRange(0, 0); document.Content.Text = frm1.lorems[rLorem1] + "\r\n"; // adding some delay if (frm1.addDelay) { Thread.Sleep(frm1.addDelaySec * 1000); } document.Content.Text = frm1.lorems[rLorem2] + "\r\n"; document.Content.Text = frm1.lorems[rLorem3]; //Add paragraph with Heading 1 style Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref winWordMissing); object styleHeading1 = "Heading 1"; para1.Range.set_Style(ref styleHeading1); para1.Range.Text = frm1.lorems[rLorem1]; para1.Range.InsertParagraphAfter(); //Add paragraph with Heading 2 style Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref winWordMissing); object styleHeading2 = "Heading 2"; para2.Range.set_Style(ref styleHeading2); para2.Range.Text = frm1.lorems[rLorem2]; para2.Range.InsertParagraphAfter(); //Save the document object filename = workingDir + wordFileNameDateFinal + ".docx"; //object filename = filePath + "\\" + fileName + ".docx"; document.SaveAs2(ref filename); // Keeping a list of files created frm1.listOfWordFiles.Add(filename.ToString()); document.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing); document = null; if (document != null) { Marshal.ReleaseComObject(document); } } else // ~~~~~~ create word files (NO formatting) { //adding text to document Random r = new Random(DateTime.Now.Millisecond); int rLorem1 = r.Next(0, 5); int rLorem2 = r.Next(0, 5); int rLorem3 = r.Next(0, 5); //Create a new document Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref winWordMissing, ref winWordMissing, ref winWordMissing, ref winWordMissing); document.Content.SetRange(0, 0); document.Content.Text = frm1.lorems[rLorem1] + "\r\n"; // adding some delay if (frm1.addDelay) { Thread.Sleep(frm1.addDelaySec * 1000); } document.Content.Text = frm1.lorems[rLorem2] + "\r\n"; document.Content.Text = frm1.lorems[rLorem3]; //Save the document object filename = workingDir + wordFileNameDateFinal + ".docx"; //object filename = filePath + "\\" + fileName + ".docx"; document.SaveAs2(ref filename); // Keeping a list of files created frm1.listOfWordFiles.Add(filename.ToString()); document.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing); document = null; if (document != null) { Marshal.ReleaseComObject(document); } } } catch (Exception ex) { Console.WriteLine("Error creating Word file!"); Console.WriteLine(ex.Message); } documentCount++; } // ~~~~~~ copy some of the documents int i2 = 0; while (i2 < filesToCreateTemp) { if (i2 % 4 == 0) { string filePathNoExtension = frm1.listOfWordFiles[i2].Substring(0, frm1.listOfWordFiles[i2].Length - 5); string newFilePathCopy = filePathNoExtension + "_copy" + ".docx"; try { var originalDocument = winword.Documents.Open(frm1.listOfWordFiles[i2]); // Open original document originalDocument.ActiveWindow.Selection.WholeStory(); // Select all in original document var originalText = originalDocument.ActiveWindow.Selection; // Copy everything to the variable var newDocument = new Word.Document(); // Create new Word document newDocument.Range().Text = originalText.Text; // Pasete everything from the variable newDocument.SaveAs(newFilePathCopy); // maybe SaveAs2?? // Save the new document originalDocument.Close(false); newDocument.Close(); if (originalDocument != null) { Marshal.ReleaseComObject(originalDocument); } if (newDocument != null) { Marshal.ReleaseComObject(newDocument); } } catch (Exception ex) { Console.WriteLine("Error coping documents"); Console.WriteLine(ex.Message); } } i2++; } // ~~~~~~ find-replace in some documents int i3 = 0; while (i3 < filesToCreateTemp) { if (i3 % 3 == 0) { try { Microsoft.Office.Interop.Word.Document aDoc = winword.Documents.Open(frm1.listOfWordFiles[i3], ReadOnly: false, Visible: false); aDoc.Activate(); winword.Selection.Find.Execute(frm1.textToSearch1, false, true, false, false, false, true, 1, false, frm1.textToReplace1, 2, false, false, false, false); winword.Selection.Find.Execute(frm1.textToSearch2, false, true, false, false, false, true, 1, false, frm1.textToReplace2, 2, false, false, false, false); aDoc.SaveAs2(); aDoc.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing); aDoc = null; if (aDoc != null) { Marshal.ReleaseComObject(aDoc); } } catch (Exception ex) { Console.WriteLine("Error in find-replace"); Console.WriteLine(ex.Message); } } i3++; } // ~~~~~~~~~~~~~~~~~~~~ Terminating Word instance ~~~~~~~~~~~~~~~~~~~ winword.Quit(ref winWordMissing, ref winWordMissing, ref winWordMissing); winword.Quit(); if (winword != null) { Marshal.ReleaseComObject(winword); } winword = null; winWordMissing = null; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ } catch (Exception ex) { Console.WriteLine("backGroundWorker WordCreate Error"); Console.WriteLine(ex.Message); } tskCreateWordsRunning = false; Console.WriteLine(); Console.WriteLine("runEverything(): createWords() -> DONE"); }
//формирование отчета в word private void button6_Click(object sender, EventArgs e) { try { Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application(); winword.Visible = false; //Заголовок документа winword.Documents.Application.Caption = "Очередь деталей для заказа"; object missing = System.Reflection.Missing.Value; //Создание нового документа Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing); //Добавление текста со стилем Обычный Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing); object styleHeading1 = "Обычный"; para1.Range.set_Style(styleHeading1); para1.Range.Font.Name = "Times New Roman"; para1.Range.Font.Size = 20; para1.Range.Text = Environment.NewLine + "Очередь деталей"; para1.Range.InsertParagraphAfter(); //Создание таблицы Table firstTable = document.Tables.Add(para1.Range, dataGridView1.RowCount, 7, ref missing, ref missing); firstTable.Borders.Enable = 1; foreach (Row row in firstTable.Rows) { foreach (Cell cell in row.Cells) { //Заголовок таблицы if (cell.RowIndex == 1) { firstTable.Cell(1, 1).Range.Text = "№ детали"; firstTable.Cell(1, 2).Range.Text = "Наименование"; firstTable.Cell(1, 3).Range.Text = "Количество"; firstTable.Cell(1, 4).Range.Text = "Стоимость 1 детали"; firstTable.Cell(1, 5).Range.Text = "Общая стоимость"; firstTable.Cell(1, 6).Range.Text = "Поставщик"; firstTable.Cell(1, 7).Range.Text = "Статус"; cell.Range.Font.Bold = 1; //Задаем шрифт и размер текста cell.Range.Font.Name = "Times New Roman"; cell.Range.Font.Size = 12; cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25; //Выравнивание текста в заголовках столбцов по центру cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } } } firstTable.Range.Font.Name = "Times New Roman"; firstTable.Range.Font.Size = 12; //Значения ячеек for (int Row = 2; Row <= dataGridView1.RowCount; Row++) { firstTable.Cell(Row, 1).Range.Text = dataGridView1.Rows[Row - 2].Cells[0].Value.ToString(); firstTable.Cell(Row, 2).Range.Text = dataGridView1.Rows[Row - 2].Cells[1].Value.ToString(); firstTable.Cell(Row, 3).Range.Text = dataGridView1.Rows[Row - 2].Cells[2].Value.ToString(); firstTable.Cell(Row, 4).Range.Text = dataGridView1.Rows[Row - 2].Cells[3].Value.ToString(); firstTable.Cell(Row, 5).Range.Text = dataGridView1.Rows[Row - 2].Cells[4].Value.ToString(); firstTable.Cell(Row, 6).Range.Text = dataGridView1.Rows[Row - 2].Cells[5].Value.ToString(); firstTable.Cell(Row, 7).Range.Text = dataGridView1.Rows[Row - 2].Cells[6].Value.ToString(); } // подпись клиента Microsoft.Office.Interop.Word.Paragraph para9 = document.Content.Paragraphs.Add(ref missing); object styleHeading9 = "Обычный"; para9.Range.set_Style(styleHeading9); para9.Range.Font.Name = "Times New Roman"; para9.Range.Font.Size = 14; para9.Range.Text = Environment.NewLine + Environment.NewLine + Environment.NewLine + " Подпись клиента: ___________________" + Environment.NewLine + " Подпись директора: ___________________"; para9.Range.InsertParagraphAfter(); // winword.Visible = true; app.Quit(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void testFichierWord() { Microsoft.Office.Interop.Word.Application msWord = new Microsoft.Office.Interop.Word.Application(); msWord.Visible = true; // mettez cette variable à true si vous souhaitez visualiser les opérations. object missing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Document nvDoc; // Choisir le template // object templateName = @"proALPHA\proALPHA_Konzept.dot"; object templateName = @"Test2.dotx"; // Créer le document nvDoc = msWord.Documents.Add(ref templateName, ref missing, ref missing, ref missing); /* HashSet<string> hash = new HashSet<string>(); foreach (Microsoft.Office.Interop.Word.FormField f in nvDoc.FormFields) { hash.Add(f.Name); } // Opérations // Les champs de formulaire définis dans le modèle se nomment "Nom" et "Prenom". object field = "Text1"; nvDoc.FormFields.get_Item(ref field).Result = "1"; field = "Text2"; nvDoc.FormFields.get_Item(ref field).Result = "2"; */ /* // Le texte que je transfère string monContenu = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl {\f0\fswiss\fcharset0 Arial;}{\f1\fnil\fcharset0 Arial;} {\f2\fmodern\fprq1\fcharset0 Courier;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Msftedit 5.41.15.1503;} \cf1\b\i\f2 Le texte que je transfère\cf0\b0\i0\f0}"; DataObject clipData = new DataObject(DataFormats.Rtf,monContenu); Clipboard.SetDataObject(clipData,false); */ /* string monContenu = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl {\f0\fswiss\fcharset0 Arial;}{\f1\fnil\fcharset0 Arial;} {\f2\fmodern\fprq1\fcharset0 Courier;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Msftedit 5.41.15.1503;} \cf1\b\i\f2 Le texte que je transfère\cf0\b0\i0\f0}"; DataObject clipData = new DataObject(DataFormats.Rtf,monContenu); Clipboard.SetDataObject(clipData,false); msWord.Selection.Paste(); */ object field = "Text1"; nvDoc.FormFields.get_Item(ref field).Result = "Checklist : "; Microsoft.Office.Interop.Word.Paragraph description = nvDoc.Content.Paragraphs.Add(ref missing); description.Range.Text = "Description"; description.Range.InsertParagraphAfter(); // Attribuer le nom object fileName = @"C:\Users\philippe_m\Documents\Projet M1\TestWord\test.doc"; // Sauver le document nvDoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); // Fermer le document nvDoc.Close(ref missing, ref missing, ref missing); msWord.Quit(ref missing, ref missing, ref missing); }
//формирование отчета в ворд private void button4_Click(object sender, EventArgs e) { try { if (textBox9.Text == String.Empty) { MessageBox.Show("Чтобы построить отчёт укажите номер заказа!"); } else { Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application(); winword.Visible = false; //Заголовок документа winword.Documents.Application.Caption = "Оформление заказа"; object missing = System.Reflection.Missing.Value; //Создание нового документа Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing); //Добавление текста со стилем Обычный Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing); object styleHeading1 = "Обычный"; para1.Range.set_Style(styleHeading1); para1.Range.Font.Name = "Times New Roman"; para1.Range.Font.Size = 20; para1.Range.Text = Environment.NewLine + "Заказ: № " + textBox9.Text; para1.Range.InsertParagraphAfter(); //Создание таблицы Table firstTable = document.Tables.Add(para1.Range, dataGridView1.RowCount, 6, ref missing, ref missing); firstTable.Borders.Enable = 1; foreach (Row row in firstTable.Rows) { foreach (Cell cell in row.Cells) { //Заголовок таблицы if (cell.RowIndex == 1) { firstTable.Cell(1, 1).Range.Text = "№ детали"; firstTable.Cell(1, 2).Range.Text = "Наименование"; firstTable.Cell(1, 3).Range.Text = "Количество"; firstTable.Cell(1, 4).Range.Text = "Стоимость 1 детали"; firstTable.Cell(1, 5).Range.Text = "Общая сумма"; firstTable.Cell(1, 6).Range.Text = "Исполняющий мастер"; cell.Range.Font.Bold = 1; //Задаем шрифт и размер текста cell.Range.Font.Name = "Times New Roman"; cell.Range.Font.Size = 12; cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25; //Выравнивание текста в заголовках столбцов по центру cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } } } firstTable.Range.Font.Name = "Times New Roman"; firstTable.Range.Font.Size = 12; //Значения ячеек for (int Row = 2; Row <= dataGridView1.RowCount; Row++) { firstTable.Cell(Row, 1).Range.Text = dataGridView1.Rows[Row - 2].Cells[0].Value.ToString(); firstTable.Cell(Row, 2).Range.Text = dataGridView1.Rows[Row - 2].Cells[1].Value.ToString(); firstTable.Cell(Row, 3).Range.Text = dataGridView1.Rows[Row - 2].Cells[2].Value.ToString(); firstTable.Cell(Row, 4).Range.Text = dataGridView1.Rows[Row - 2].Cells[3].Value.ToString(); firstTable.Cell(Row, 5).Range.Text = dataGridView1.Rows[Row - 2].Cells[4].Value.ToString(); firstTable.Cell(Row, 6).Range.Text = dataGridView1.Rows[Row - 2].Cells[5].Value.ToString(); } Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing); object styleHeading2 = "Обычный"; para2.Range.set_Style(styleHeading2); para2.Range.Font.Name = "Times New Roman"; para2.Range.Font.Size = 14; para2.Range.Text = ""; para2.Range.InsertParagraphAfter(); //Создание таблицы Table firstTable2 = document.Tables.Add(para1.Range, dataGridView2.RowCount, 4, ref missing, ref missing); firstTable2.Borders.Enable = 1; foreach (Row row in firstTable2.Rows) { foreach (Cell cell in row.Cells) { //Заголовок таблицы if (cell.RowIndex == 1) { firstTable2.Cell(1, 1).Range.Text = "№ услуги"; firstTable2.Cell(1, 2).Range.Text = "Наименование"; firstTable2.Cell(1, 3).Range.Text = "Стоимость"; firstTable2.Cell(1, 4).Range.Text = "Исполняющий мастер"; cell.Range.Font.Bold = 1; //Задаем шрифт и размер текста cell.Range.Font.Name = "Times New Roman"; cell.Range.Font.Size = 12; cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25; //Выравнивание текста в заголовках столбцов по центру cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } } } firstTable2.Range.Font.Name = "Times New Roman"; firstTable2.Range.Font.Size = 12; //Значения ячеек for (int Row = 2; Row <= dataGridView2.RowCount; Row++) { firstTable2.Cell(Row, 1).Range.Text = dataGridView2.Rows[Row - 2].Cells[0].Value.ToString(); firstTable2.Cell(Row, 2).Range.Text = dataGridView2.Rows[Row - 2].Cells[1].Value.ToString(); firstTable2.Cell(Row, 3).Range.Text = dataGridView2.Rows[Row - 2].Cells[2].Value.ToString(); firstTable2.Cell(Row, 4).Range.Text = dataGridView2.Rows[Row - 2].Cells[3].Value.ToString(); } Microsoft.Office.Interop.Word.Paragraph para3 = document.Content.Paragraphs.Add(ref missing); object styleHeading3 = "Обычный"; para3.Range.set_Style(styleHeading3); para3.Range.Font.Name = "Times New Roman"; para3.Range.Font.Size = 14; para3.Range.Text = Environment.NewLine + "Номер клиента: " + textBox8.Text + Environment.NewLine + "Номер заказа: " + textBox9.Text + Environment.NewLine + "Стоимость: " + textBox10.Text + Environment.NewLine + "Дата оформления: " + dateTimePicker1.Value.Date.ToShortDateString() + Environment.NewLine + "Дата закрытия: " + dateTimePicker2.Value.Date.ToShortDateString() + Environment.NewLine + Environment.NewLine + Environment.NewLine; para3.Range.InsertParagraphAfter(); // подпись клиента Microsoft.Office.Interop.Word.Paragraph para9 = document.Content.Paragraphs.Add(ref missing); object styleHeading9 = "Обычный"; para9.Range.set_Style(styleHeading9); para9.Range.Font.Name = "Times New Roman"; para9.Range.Font.Size = 14; para9.Range.Text = " Подпись клиента: ___________________" + Environment.NewLine + " Подпись директора: ___________________"; para9.Range.InsertParagraphAfter(); // winword.Visible = true; app.Quit(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static void Otchet4(List <string[]> arr) { Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application(); winword.Visible = false; //Заголовок документа winword.Documents.Application.Caption = "Незавершенка"; object missing = System.Reflection.Missing.Value; //Создание нового документа Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing); //Добавление текста со стилем Заголовок 1 Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing); //object styleHeading1 = "Заголовок 1"; //para1.Range.set_Style(styleHeading1); para1.Range.Text = "Незавершенка"; para1.Range.Bold = 1; para1.Range.Font.Size = 16; para1.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; para1.Range.InsertParagraphAfter(); //Создание таблицы 5х5 Word.Table firstTable = document.Tables.Add(para1.Range, arr.Count + 1, 2, ref missing, ref missing); firstTable.Borders.Enable = 1; foreach (Word.Row row in firstTable.Rows) { foreach (Word.Cell cell in row.Cells) { //Заголовок таблицы if (cell.RowIndex == 1) { if (cell.ColumnIndex == 1) { cell.Range.Text = "Название детали"; } else { cell.Range.Text = "Кол-во незавершенных экземпляров"; } //cell.Range.Text = "Колонка " + cell.ColumnIndex.ToString(); cell.Range.Font.Bold = 1; //Задаем шрифт и размер текста cell.Range.Font.Name = "verdana"; cell.Range.Font.Size = 12; cell.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray25; //Выравнивание текста в заголовках столбцов по центру cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } //Значения ячеек else { cell.Range.Font.Name = "verdana"; cell.Range.Font.Size = 12; cell.Range.Font.Bold = 0; if (cell.ColumnIndex == 1) { cell.Range.Text = arr[cell.RowIndex - 2][0]; } else { cell.Range.Text = arr[cell.RowIndex - 2][1]; } //cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString(); } } } //Сохранение документа object filename = "D:\\4 курс\\1 семестр\\Горохов\\Lab6\\Wordik\\Позор бракоделам"; document.SaveAs(ref filename); winword.Visible = true; document = null; }
public static void Otchet1(List <string[]> arr) { Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application(); winword.Visible = false; //Заголовок документа winword.Documents.Application.Caption = "Производство за заданный период"; object missing = System.Reflection.Missing.Value; //Создание нового документа Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing); //добавление новой страницы //winword.Selection.InsertNewPage(); ////Добавление верхнего колонтитула //foreach (Microsoft.Office.Interop.Word.Section section in document.Sections) //{ // Microsoft.Office.Interop.Word.Range headerRange = section.Headers[ // Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; // headerRange.Fields.Add( // headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage); // headerRange.ParagraphFormat.Alignment = // Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; // headerRange.Font.ColorIndex = // Microsoft.Office.Interop.Word.WdColorIndex.wdBlue; // headerRange.Font.Size = 10; // headerRange.Text = "Верхний колонтитул" + Environment.NewLine + "www.CSharpCoderR.com"; //} ////Добавление нижнего колонтитула //foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections) //{ // // // Microsoft.Office.Interop.Word.Range footerRange = // wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; // //Установка цвета текста // footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed; // //Размер // footerRange.Font.Size = 10; // //Установка расположения по центру // footerRange.ParagraphFormat.Alignment = // Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; // //Установка текста для вывода в нижнем колонтитуле // footerRange.Text = "Нижний колонтитул" + Environment.NewLine + "www.CSharpCoderR.com"; //} ////Добавление текста в документ //document.Content.SetRange(0, 0); //document.Content.Text = "www.CSharpCoderR.com" + Environment.NewLine; //Добавление текста со стилем Заголовок 1 Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing); //object styleHeading1 = "Заголовок 1"; //para1.Range.set_Style(styleHeading1); para1.Range.Text = "Производство за заданный период"; para1.Range.Bold = 1; para1.Range.Font.Size = 16; para1.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; para1.Range.InsertParagraphAfter(); //Создание таблицы 5х5 Word.Table firstTable = document.Tables.Add(para1.Range, arr.Count + 1, 2, ref missing, ref missing); firstTable.Borders.Enable = 1; foreach (Word.Row row in firstTable.Rows) { foreach (Word.Cell cell in row.Cells) { //Заголовок таблицы if (cell.RowIndex == 1) { if (cell.ColumnIndex == 1) { cell.Range.Text = "Название детали"; } else { cell.Range.Text = "Кол-во экземпляров"; } //cell.Range.Text = "Колонка " + cell.ColumnIndex.ToString(); cell.Range.Font.Bold = 1; //Задаем шрифт и размер текста cell.Range.Font.Name = "verdana"; cell.Range.Font.Size = 12; cell.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray25; //Выравнивание текста в заголовках столбцов по центру cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } //Значения ячеек else { cell.Range.Font.Name = "verdana"; cell.Range.Font.Size = 12; cell.Range.Font.Bold = 0; if (cell.ColumnIndex == 1) { cell.Range.Text = arr[cell.RowIndex - 2][0]; } else { cell.Range.Text = arr[cell.RowIndex - 2][1]; } //cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString(); } } } //Сохранение документа object filename = "D:\\4 курс\\1 семестр\\Горохов\\Lab6\\Wordik\\Производство за заданный период"; document.SaveAs(ref filename); winword.Visible = true; //Закрытие текущего документа //document.Close(ref missing, ref missing, ref missing); document = null; //Закрытие приложения Word //winword.Quit(ref missing, ref missing, ref missing); //winword = null; //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message); //} }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { string result = string.Empty; Word.Application app_res = new Word.Application(); Word.Document doc_res = new Word.Document(); app_res.Visible = false; app_res.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; object nullobject = System.Reflection.Missing.Value; Object pathToSaveObj = Directory.GetCurrentDirectory() + "\\Result.docx"; doc_res.SaveAs(ref pathToSaveObj, Word.WdSaveFormat.wdFormatDocumentDefault, ref nullobject, ref nullobject, ref nullobject, ref nullobject, false, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject); if (!File.Exists(Directory.GetCurrentDirectory() + "\\Result.docx")) { doc_res = app_res.Documents.Add(ref nullobject, ref nullobject, ref nullobject, ref nullobject); } else { doc_res = app_res.Documents.Open(Directory.GetCurrentDirectory() + "\\Result.docx"); } vOutput("Создали выходной файл " + Directory.GetCurrentDirectory() + "\\Result.docx" + Environment.NewLine); int i = 0; foreach (DataRow row in dataSet1.Tables[0].Rows) { string filename = string.Format("orig{0}", row.ItemArray[0].ToString()); string[] f = Directory.GetFiles(Directory.GetCurrentDirectory() + "\\docs", filename + "*"); //Word.Application wordObject = new Word.Application(); object File = f[0]; Word.Application wordobject = new Word.Application(); wordobject.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; Word.Document docs = new Word.Document(); //wordobject.Visible = false; try { // docs = wordobject.Documents.Open(ref File, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject); //docs.ActiveWindow.Selection.WholeStory(); //docs.ActiveWindow.Selection.Copy(); //Thread.Sleep(500); // object temp = Clipboard.GetData(""); Microsoft.Office.Interop.Word.Paragraph para1 = doc_res.Content.Paragraphs.Add(ref nullobject); // object styleHeading1 = "Заголовок 2"; //para1.Range.set_Style(styleHeading1); para1.Range.InsertParagraph(); para1.Range.Font.Size = 14; para1.Range.Font.Name = "Times New Roman"; para1.Format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; para1.Range.Text = row.ItemArray[1].ToString(); para1.Range.InsertParagraphAfter(); doc_res.Save(); para1.Range.Font.Size = 12; para1.Range.Font.Name = "Times New Roman"; para1.Format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; //para1.Range.Text = row.ItemArray[1].ToString(); para1.Range.Text = row.ItemArray[3].ToString(); para1.Range.InsertParagraphAfter(); doc_res.Save(); para1.Range.Font.Size = 16; para1.Range.Font.Name = "Times New Roman"; para1.Format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; para1.Range.Font.Bold = 1; para1.Range.Text = row.ItemArray[2].ToString(); para1.Range.InsertParagraphAfter(); doc_res.Save(); ////object missing = Missing.Value; //object what = Word.WdGoToItem.wdGoToLine; //object which = Word.WdGoToDirection.wdGoToLast; //Word.Range endRange = doc_res.GoTo(ref what, ref which, ref nullobject, ref nullobject); //para1.Range.Paste(); app_res.Selection.GoTo(Word.WdGoToItem.wdGoToLine, Word.WdGoToDirection.wdGoToLast, ref nullobject, ref nullobject); app_res.Selection.InsertFile(f[0]); //doc_res.ActiveWindow.Selection.Paste(); Thread.Sleep(200); doc_res.Save(); string output = string.Format("Добавили файл {0} в выходной файл", f[0]); vOutput(output + Environment.NewLine); //richTextBox1.Text += Environment.NewLine + Environment.NewLine + row.Cells[1].Value.ToString() + Environment.NewLine + row.Cells[3].Value.ToString() + Environment.NewLine + row.Cells[2].Value.ToString() + Environment.NewLine; // richTextBox1.Paste(); // rtfMain.Document.Paste(); // Thread.Sleep(200); docs.Close(ref nullobject, ref nullobject, ref nullobject); //Thread.Sleep(200); wordobject.Quit(ref nullobject, ref nullobject, ref nullobject); // Thread.Sleep(200); backgroundWorker1.ReportProgress(i); i++; } catch (Exception error) { docs.Close(); wordobject.Quit(ref nullobject, ref nullobject, ref nullobject); // Thread.Sleep(200); //wordobject.Quit(ref nullobject, ref nullobject, ref nullobject); vOutput("Проблема с файлом: " + f[0] + " " + error.Message + Environment.NewLine); backgroundWorker1.ReportProgress(i); i++; //return; //throw error; } } //Object pathToSaveObj = Directory.GetCurrentDirectory() + "\\Result.docx"; //doc_res.SaveAs(ref pathToSaveObj, Word.WdSaveFormat.wdFormatDocumentDefault, ref nullobject, ref nullobject, ref nullobject, // ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, // ref nullobject, ref nullobject, ref nullobject, ref nullobject); app_res.Visible = true; }
private void CreateDocument() { try { Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application(); winword.Visible = false; object missing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing); foreach (Microsoft.Office.Interop.Word.Section section in document.Sections) { Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue; headerRange.Font.Size = 10; headerRange.Text = "Header text goes here"; } foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections) { Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed; footerRange.Font.Size = 10; footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; footerRange.Text = "Footer text goes here"; } document.Content.SetRange(0, 0); document.Content.Text = "This is test document " + Environment.NewLine; Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing); object styleHeading1 = "Heading 1"; para1.Range.set_Style(ref styleHeading1); para1.Range.Text = "Para 1 text"; para1.Range.InsertParagraphAfter(); Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing); object styleHeading2 = "Heading 2"; para2.Range.set_Style(ref styleHeading2); para2.Range.Text = "Neve: #NEV#"; para2.Range.InsertParagraphAfter(); Word.Table firstTable = document.Tables.Add(para1.Range, 3, 2, ref missing, ref missing); firstTable.Borders.Enable = 1; foreach (Row row in firstTable.Rows) { foreach (Cell cell in row.Cells) { if (cell.RowIndex == 1) { cell.Range.Text = "Column " + cell.ColumnIndex.ToString(); cell.Range.Font.Bold = 1; cell.Range.Font.Name = "verdana"; cell.Range.Font.Size = 10; cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25; cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } else { cell.Range.Text = "Tartalom " + (cell.RowIndex - 2 + cell.ColumnIndex).ToString(); } } } object filename = @"d:\temp1.docx"; document.SaveAs(ref filename); document.Close(ref missing, ref missing, ref missing); document = null; winword.Quit(ref missing, ref missing, ref missing); winword = null; System.Windows.Forms.MessageBox.Show("Document created successfully !"); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } }