private static void makeExamIntro(ref W.Document doc, string qrCodeJPG, string Intro, string Title) { W.Range aux = null; aux = doc.Range(0, Type.Missing); aux.Text = Title; ///TITULO aux.set_Style(W.WdBuiltinStyle.wdStyleHeading1); aux.InsertParagraphAfter(); doc.Paragraphs.Add(aux); aux = doc.Paragraphs.Last.Range; object lastRange = aux; aux.InlineShapes.AddPicture(qrCodeJPG, ref roObj, ref roObj, ref lastRange); aux.InlineShapes.AddPicture(ID_FILE, ref roObj, ref roObj, ref lastRange); aux.set_Style(W.WdBuiltinStyle.wdStyleCaption); //title style for image??? aux.InsertParagraphAfter(); doc.Paragraphs.Add(aux); //esto no estaba /////TITULOOOOOOOOOOOO if (string.IsNullOrEmpty(Intro)) { return; } aux = doc.Paragraphs.Last.Range; aux.Text = Intro; aux.set_Style(W.WdBuiltinStyle.wdStyleFooter); aux.InsertParagraphAfter(); doc.Paragraphs.Add(aux); // aux = doc.Paragraphs.Last.Range; }
//</Snippet82> //--------------------------------------------------------------------- //<Snippet89> private void CreateDocumentPropertyTable() { //<Snippet90> object start = 0, end = 0; Word.Document document = this.Application.ActiveDocument; Word.Range rng = document.Range(ref start, ref end); //</Snippet90> // Insert a title for the table and paragraph marks. //<Snippet91> rng.InsertBefore("Document Statistics"); rng.Font.Name = "Verdana"; rng.Font.Size = 16; rng.InsertParagraphAfter(); rng.InsertParagraphAfter(); rng.SetRange(rng.End, rng.End); //</Snippet91> // Add the table. //<Snippet92> rng.Tables.Add(document.Paragraphs[2].Range, 3, 2, ref missing, ref missing); //</Snippet92> // Format the table and apply a style. //<Snippet93> Word.Table tbl = document.Tables[1]; tbl.Range.Font.Size = 12; tbl.Columns.DistributeWidth(); object styleName = "Table Professional"; tbl.set_Style(ref styleName); //</Snippet93> // Insert document properties into cells. //<Snippet94> tbl.Cell(1, 1).Range.Text = "Document Property"; tbl.Cell(1, 2).Range.Text = "Value"; tbl.Cell(2, 1).Range.Text = "Subject"; tbl.Cell(2, 2).Range.Text = ((Office.DocumentProperties)(document.BuiltInDocumentProperties)) [Word.WdBuiltInProperty.wdPropertySubject].Value.ToString(); tbl.Cell(3, 1).Range.Text = "Author"; tbl.Cell(3, 2).Range.Text = ((Office.DocumentProperties)(document.BuiltInDocumentProperties)) [Word.WdBuiltInProperty.wdPropertyAuthor].Value.ToString(); //</Snippet94> }
public Action AddToWordDocument(IResumeDataObject rdo, IResumeFormatObject rfo, Word.Document wordDoc) { return(() => { // Education label Word.Paragraph educationLabelPara = wordDoc.Content.Paragraphs.Add(); Word.Range r6label = educationLabelPara.Range; r6label.Text = "Education"; r6label.InsertParagraphAfter(); r6label.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; r6label.Font.Name = rfo.HeaderFontName; r6label.Font.Color = rfo.HeaderColorWord; r6label.Font.Size = rfo.HeaderFontSize; // Education items int numEduc = rdo.EducationEntities.Count; for (int i = 0; i < numEduc; i++) { Word.Paragraph educParagraph = wordDoc.Content.Paragraphs.Add(); Word.Range r6 = educParagraph.Range; r6.Text = rdo.EducationEntities[i].Credential + ", " + rdo.EducationEntities[i].Institution; r6.InsertParagraphAfter(); r6.Font.Name = rfo.BodyFontName; r6.Font.Size = rfo.BodyFontSize; r6.ParagraphFormat.SpaceAfter = 8; r6.ParagraphFormat.SpaceBefore = 8; } }); }
public Action AddToWordDocument(IResumeDataObject rdo, IResumeFormatObject rfo, Word.Document wordDoc) { return(() => { if (rdo.PublicationEntities.Count > 0) { // Publications label Word.Paragraph pubsLabelPara = wordDoc.Content.Paragraphs.Add(); Word.Range r7label = pubsLabelPara.Range; r7label.Text = "Selected Publications"; r7label.InsertParagraphAfter(); r7label.Font.Name = rfo.HeaderFontName; r7label.Font.Color = rfo.HeaderColorWord; r7label.Font.Size = rfo.HeaderFontSize; // Publication items int numPub = rdo.PublicationEntities.Count; for (int i = 0; i < numPub; i++) { Word.Paragraph pubParagraph = wordDoc.Content.Paragraphs.Add(); Word.Range r7 = pubParagraph.Range; r7.Text = rdo.PublicationEntities[i].Publication; r7.InsertParagraphAfter(); r7.Font.Name = rfo.BodyFontName; r7.Font.Size = rfo.BodyFontSize; r7.ParagraphFormat.SpaceAfter = 8; r7.ParagraphFormat.SpaceBefore = 8; } } }); }
internal static void CreateLine <T>(this T lc, MWord.Range range, WdOMathJc justify = WdOMathJc.wdOMathJcLeft, int fontsize = 12, int leftIndent = 0, int spaceAfter = 0, int bold = 0) where T : LineContent { switch (lc) { case LineText lt: lt.WriteLine(range, justify, fontsize, leftIndent * (int)lc.TabIndex, spaceAfter, bold); break; case LineTable lta: lta.WriteLine(range, fontsize); break; case LinePicture lp: lp.WriteLine(range); break; case LineCanvas ls: ls.WriteLine(range); break; case CurveCanvasShape ccs: ccs.DrawShapeOnDoc(range.Document); break; case LineCanvasShape lcs: lcs.DrawShapeOnDoc(range.Document); break; case TriangleCanvasShape tcs: tcs.DrawShapeOnDoc(range.Document); break; } range.InsertParagraphAfter(); }
/// <summary> /// 新起一段 /// </summary> /// <param name="range">Range对象,可以为选区范围或者光标插入点</param> /// <param name="PrphStyle">新起一段的段落样式</param> /// <remarks></remarks> private void NewLine(Word.Range range, string PrphStyle) { Word.Range with_1 = range; with_1.Collapse(Word.WdCollapseDirection.wdCollapseEnd); with_1.InsertParagraphAfter(); with_1.Collapse(Word.WdCollapseDirection.wdCollapseEnd); with_1.ParagraphFormat.set_Style(PrphStyle); }
private void insertText(Word._Document oDoc, string text) { log("Inserting Text: " + text); object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; //Add text after the chart. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter(text); }
public Action AddToWordDocument(IResumeDataObject rdo, IResumeFormatObject rfo, Word.Document wordDoc) { return(() => { // Experience label Word.Paragraph experienceLabelPara = wordDoc.Content.Paragraphs.Add(); Word.Range r5label = experienceLabelPara.Range; r5label.Text = "Experience"; r5label.InsertParagraphAfter(); r5label.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; r5label.Font.Name = rfo.HeaderFontName; r5label.Font.Color = rfo.HeaderColorWord; r5label.Font.Size = rfo.HeaderFontSize; // Experience items int numJobs = rdo.ExperienceEntities.Count; for (int i = 0; i < numJobs; i++) { // Job metadata Word.Paragraph experienceParagraph = wordDoc.Content.Paragraphs.Add(); Word.Range r5 = experienceParagraph.Range; r5.Text = rdo.ExperienceEntities[i].Employer + Environment.NewLine + rdo.ExperienceEntities[i].Titles[0] + Environment.NewLine + rdo.ExperienceEntities[i].StartDate + " - " + rdo.ExperienceEntities[i].EndDate; r5.Font.Name = rfo.JobInfoFontName; r5.Font.Color = rfo.JobInfoColorWord; r5.Font.Size = rfo.JobInfoFontSize; r5.ParagraphFormat.SpaceAfter = 0; r5.ParagraphFormat.SpaceBefore = 0; // Add experience details int numDetails = rdo.ExperienceEntities[i].Details.Count; Word.Paragraph detPara = wordDoc.Content.Paragraphs.Add(); Word.Range r = detPara.Range; for (int j = 0; j < numDetails; j++) { Word.Paragraph expItemPara = wordDoc.Content.Paragraphs.Add(); Word.Range r5Item = expItemPara.Range; r5Item.Text = rdo.ExperienceEntities[i].Details[j]; r5Item.InsertParagraphAfter(); r5Item.Font.Name = rfo.BodyFontName; r5Item.Font.Size = rfo.BodyFontSize; r5Item.ParagraphFormat.LeftIndent = 20.0F; r5Item.ParagraphFormat.SpaceAfter = 8; r5Item.ParagraphFormat.SpaceBefore = 8; } } }); }
public Action AddToWordDocument(IResumeDataObject rdo, IResumeFormatObject rfo, Word.Document wordDoc) { return(() => { Word.Paragraph fullNamePara = wordDoc.Content.Paragraphs.Add(); Word.Range r1 = fullNamePara.Range; r1.Text = rdo.FullName; r1.InsertParagraphAfter(); r1.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; r1.Font.Name = rfo.NameFontName; r1.Font.Color = rfo.NameColorWord; r1.Font.Size = rfo.NameFontSize; }); }
public void CriarTabela(int numLinhas, int numColunas) { object start = 0, end = 0; //Word.Range rng = Documento.Range(ref start, ref end); Word.Range rng = Documento.Application.Selection.Range; // Configura o local onde será inserido a tabela rng.Font.Name = "Calibri"; rng.Font.Size = 11; rng.InsertParagraphAfter(); rng.SetRange(rng.End, rng.End); // Add a tabela, formata e coloca bordas na tabela rng.Tables.Add(Documento.Paragraphs[rng.Start].Range, numLinhas, numColunas, Word.WdLineStyle.wdLineStyleSingle); }
public Action AddToWordDocument(IResumeDataObject rdo, IResumeFormatObject rfo, Word.Document wordDoc) { return(() => { if (rdo.ExpertiseEntities.Count > 0) { // Expertise label Word.Paragraph tagLineLabelPara = wordDoc.Content.Paragraphs.Add(); Word.Range r4label = tagLineLabelPara.Range; r4label.Text = "Expertise"; r4label.InsertParagraphAfter(); r4label.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; r4label.Font.Name = rfo.HeaderFontName; r4label.Font.Color = rfo.HeaderColorWord; r4label.Font.Size = rfo.HeaderFontSize; // Expertise item-headers List <string> cats = rdo.ExpertiseEntities.Select(T => T.Category).Distinct().ToList(); for (int i = 0; i < cats.Count; i++) { Word.Paragraph p = wordDoc.Content.Paragraphs.Add(); Word.Range r4 = p.Range; r4.Text = cats[i] + ": "; int titleLength = r4.Text.Length; // Insert expertise(s) List <string> exps = rdo.ExpertiseEntities.Where(T => T.Category == cats[i]).Select(T => T.Expertise).ToList(); for (int j = 0; j < exps.Count; j++) { r4.Font.Name = rfo.BodyFontName; r4.Font.Size = rfo.BodyFontSize; r4.InsertAfter(exps[j] + " " + '\u2022' + " "); } r4.Text = r4.Text.Remove(r4.Text.Length - 2); Word.Range titleRange = r4.Duplicate; titleRange.MoveEnd(Word.WdUnits.wdCharacter, titleLength - 1 - titleRange.Characters.Count); titleRange.MoveStart(Word.WdUnits.wdCharacter, 0); titleRange.Font.Name = rfo.CategoryFontName; titleRange.Font.Size = rfo.CategoryFontSize; r4.InsertParagraphAfter(); } } }); }
private static void WriteLine(this LineText lt, MWord.Range range, WdOMathJc justify = WdOMathJc.wdOMathJcLeft, int fontsize = 12, int leftIndent = 0, int spaceAfter = 0, int bold = 0) { if ((lt.TextContent == null) || (lt.TextContent?.Length == 0)) { return; } range.Text = lt.TextContent; var mathRange = range.OMaths.Add(range); var currentMath = mathRange.OMaths[1]; currentMath.Range.Font.Bold = bold; currentMath.Range.Font.Size = fontsize; currentMath.Justification = justify; currentMath.BuildUp(); currentMath.Range.Paragraphs.LeftIndent = leftIndent; currentMath.Range.Paragraphs.SpaceAfter = spaceAfter; range.InsertParagraphAfter(); }
public Action AddToWordDocument(IResumeDataObject rdo, IResumeFormatObject rfo, Word.Document wordDoc) { return(() => { if (rdo.TagLine != string.Empty) { Word.Paragraph tagLinePara = wordDoc.Content.Paragraphs.Add(); Word.Range r3 = tagLinePara.Range; r3.Text = rdo.TagLine; r3.InsertParagraphAfter(); r3.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; r3.Font.Name = rfo.TagLineFontName; r3.Font.Color = rfo.TagLineColorWord; r3.Font.Size = rfo.TagLineFontSize; r3.ParagraphFormat.SpaceAfter = 12; r3.ParagraphFormat.SpaceBefore = 12; } }); }
private void AddProtectedContentControls() { this.Paragraphs[1].Range.InsertParagraphBefore(); Word.Range range1 = this.Paragraphs[1].Range; deletableControl = this.Controls.AddRichTextContentControl(range1, "deletableControl"); deletableControl.PlaceholderText = "You can delete this control, " + "but you cannot edit it"; deletableControl.LockContents = true; range1.InsertParagraphAfter(); Word.Range range2 = this.Paragraphs[2].Range; editableControl = this.Controls.AddRichTextContentControl(range2, "editableControl"); editableControl.PlaceholderText = "You can edit this control, " + "but you cannot delete it"; editableControl.LockContentControl = true; }
// вставляем пустой абзац, доступ к его тексту и свойствам через public void InsertParagraphAfter() { if (Closed) { throw new Exception("Ошибка при обращении к документу Word. Документ уже закрыт."); } // сворачиваем текущую позицию и переходим в ее конец Object collapseDirection = Word.WdCollapseDirection.wdCollapseEnd; try { _currentRange.Collapse(ref collapseDirection); //вставляем абзац _currentRange.InsertParagraphAfter(); _selection = new WordSelection(_currentRange); } catch (Exception wordError) { throw wordError; } }
private void AddProtectedContentControls() { Microsoft.Office.Tools.Word.Document vstoDocument = Globals.Factory.GetVstoObject(this.Application.ActiveDocument); vstoDocument.Paragraphs[1].Range.InsertParagraphBefore(); Word.Range range1 = vstoDocument.Paragraphs[1].Range; deletableControl = vstoDocument.Controls.AddRichTextContentControl(range1, "deletableControl"); deletableControl.PlaceholderText = "You can delete this control, " + "but you cannot edit it"; deletableControl.LockContents = true; range1.InsertParagraphAfter(); Word.Range range2 = vstoDocument.Paragraphs[2].Range; editableControl = vstoDocument.Controls.AddRichTextContentControl(range2, "editableControl"); editableControl.PlaceholderText = "You can edit this control, " + "but you cannot delete it."; editableControl.LockContentControl = true; }
private void CreateDocumentPropertyTable(Document newDocument) { //<Snippet90> object start = 10, end = 10; Word.Range rangeTbl = null; string keys = "[tbl]"; while (newDocument.Content.Find.Execute(FindText: keys)) { if (newDocument.Content.Find.Execute(FindText: keys)) { if (newDocument.Application.Selection.Find.Execute(keys) == true) { rangeTbl = newDocument.Range(newDocument.Application.Selection.Range.Start, newDocument.Application.Selection.Range.End); } } } //if (newDocument.Application.Selection.Find.Execute("[tbl]")) //{ // rangeTbl = newDocument.Range(newDocument.Application.Selection.Range.Start, newDocument.Application.Selection.Range.End); //} Word.Range rng = newDocument.Range(rangeTbl.Start, rangeTbl.End); //</Snippet90> // Insert a title for the table and paragraph marks. //<Snippet91> //rng.InsertBefore("Document Statistics"); rng.Font.Name = "Calibri (Body)"; rng.Font.Size = 16; rng.InsertParagraphAfter(); rng.InsertParagraphAfter(); rng.SetRange(rng.End, rng.End); //</Snippet91> // Add the table. //<Snippet92> rng.Tables.Add(newDocument.Paragraphs[2].Range, 3, 2); //</Snippet92> // Format the table and apply a style. //<Snippet93> Word.Table tbl = newDocument.Tables[1]; tbl.Range.Font.Size = 12; tbl.Columns.DistributeWidth(); object styleName = "Table Professional"; tbl.set_Style(ref styleName); //</Snippet93> // Insert document properties into cells. //<Snippet94> tbl.Cell(1, 1).Range.Text = "Document Property"; tbl.Cell(1, 2).Range.Text = "Value"; tbl.Cell(2, 1).Range.Text = "Subject"; tbl.Cell(2, 2).Range.Text = "Test"; tbl.Cell(3, 1).Range.Text = "Author"; tbl.Cell(3, 2).Range.Text = "test"; //</Snippet94> }
private void Export_Word_Click(object sender, RoutedEventArgs e) { var allUsers = _context.Билет.ToList(); var allCategories = _context.Клиент.ToList(); var application = new Word.Application(); Word.Document document = application.Documents.Add(); foreach (var user in allUsers) { Word.Paragraph userParagrapth = document.Paragraphs.Add(); Word.Range userRange = userParagrapth.Range; userRange.Text = user.Код_заказа + " " + user.Код_сотрудника; userParagrapth.set_Style("Обычный"); userRange.InsertParagraphAfter(); Word.Paragraph tableParagraph = document.Paragraphs.Add(); Word.Range tableRange = tableParagraph.Range; Word.Table paymentsTable = document.Tables.Add(tableRange, allCategories.Count() + 1, 3); paymentsTable.Borders.InsideLineStyle = paymentsTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; paymentsTable.Range.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; Word.Range cellRange; cellRange = paymentsTable.Cell(1, 1).Range; cellRange.Text = "Иконка"; cellRange = paymentsTable.Cell(1, 2).Range; cellRange.Text = "Категория"; cellRange = paymentsTable.Cell(1, 3).Range; cellRange.Text = "Сумма расходов"; paymentsTable.Rows[1].Range.Bold = 1; paymentsTable.Rows[1].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; for (int i = 0; i < allCategories.Count(); i++) { var currentCategory = allCategories[i]; cellRange = paymentsTable.Cell(i + 2, 1).Range; Word.InlineShape imageShape = cellRange.InlineShapes.AddPicture(AppDomain.CurrentDomain.BaseDirectory + "\\Assets\\" + currentCategory.icon); imageShape.Width = imageShape.Height = 40; cellRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; cellRange = paymentsTable.Cell(i + 2, 2).Range; cellRange.Text = currentCategory.телефон; cellRange = paymentsTable.Cell(i + 2, 3).Range; cellRange.Text = user.Заказ.ToList().Where(p => p.Код_клиента == currentCategory.Код_клиента).Sum(p => p.Код_заказа * p.Код_клиента).ToString("N2") + "руб"; } Заказ maxPayment = user.Заказ.OrderByDescending(p => p.Код_заказа * p.Код_клиента).FirstOrDefault(); if (maxPayment != null) { Word.Paragraph maxPaymentParagraph = document.Paragraphs.Add(); Word.Range maxPaymentRange = maxPaymentParagraph.Range; maxPaymentRange.Text = $"Самый дорогостоящий платеж - {maxPayment.Дата_оформления} за {(maxPayment.Код_заказа * maxPayment.Код_клиента).ToString("N2")} "; maxPaymentRange.set_Style("Выделенная цитата"); maxPaymentRange.Font.Color = Word.WdColor.wdColorDarkRed; maxPaymentRange.InsertParagraphAfter(); } Заказ minPayment = user.Заказ.OrderBy(p => p.Код_заказа * p.Код_клиента).FirstOrDefault(); if (minPayment != null) { Word.Paragraph minPaymentParagraph = document.Paragraphs.Add(); Word.Range minPaymentRange = minPaymentParagraph.Range; minPaymentRange.Text = $"Самый дешевый платеж - {minPayment.Дата_оформления} за {(minPayment.Код_заказа * minPayment.Код_клиента).ToString("N2")} "; minPaymentRange.set_Style("Выделенная цитата"); minPaymentRange.Font.Color = Word.WdColor.wdColorDarkGreen; minPaymentRange.InsertParagraphAfter(); } if (user != allUsers.LastOrDefault()) { document.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak); } } application.Visible = true; document.SaveAs(@"D:\для с#\программные решения для бизнеса\diagramms\diagramms\packages\Test.docx"); document.SaveAs(@"D:\для с#\программные решения для бизнеса\diagramms\diagramms\packages\Test.pdf", Word.WdExportFormat.wdExportFormatPDF); }
private void performOperation() { List <TableInformation> tableData = new List <TableInformation>(); var date = DateTime.Now; #region Connect To DB string statement = Constatnts.statement1; using (SqlConnection con = new SqlConnection(cs)) { SqlCommand executeStatement = new SqlCommand(statement, con); con.Open(); SqlDataReader reader = executeStatement.ExecuteReader(); while (reader.Read()) { TableInformation t = new TableInformation(); t.SynonymName = reader["Synonym_NAME"].ToString(); t.TableName = reader["Table_NAME"].ToString(); tableData.Add(t); } } List <TableInformation> sortedTableData = tableData.OrderBy(order => order.SynonymName).ToList(); #endregion #region Starting Word Application object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); #endregion //Insert a paragraph at the beginning of the document. Word.Paragraph oPara1; oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Text = "All tables are under dbo schema and all columns are not nullable."; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. oPara1.Range.InsertParagraphAfter(); #region Insert Table Information //Insert a table, fill it with data, and make the first row bold Word.Table oTable; Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, sortedTableData.Count + 1, 3, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; int r; oTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; oTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; oTable.Cell(1, 1).Range.Text = "NO"; oTable.Cell(1, 2).Range.Text = "TABLE NAME"; oTable.Cell(1, 3).Range.Text = "SYNONYM NAME"; oTable.Cell(1, 1).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray40; oTable.Cell(1, 2).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray40; oTable.Cell(1, 3).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray40; oTable.Range.Font.Bold = 0; int z = 0; for (r = 2; r <= sortedTableData.Count + 1; r++) { oTable.Cell(r, 1).Range.Text = (z + 1).ToString(); oTable.Cell(r, 2).Range.Text = sortedTableData[z].TableName; oTable.Cell(r, 3).Range.Text = sortedTableData[z].SynonymName; z++; } oTable.Rows[1].Range.Font.Bold = 1; oTable.Columns[1].PreferredWidth = oWord.InchesToPoints(0.4f); oTable.Columns[2].PreferredWidth = oWord.InchesToPoints(2.5f); oTable.Columns[3].PreferredWidth = oWord.InchesToPoints(2.3f); #endregion //Add some text after the table. Word.Paragraph oPara4; object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara4 = oDoc.Content.Paragraphs.Add(ref oRng); oPara4.Range.InsertParagraphBefore(); oPara4.Range.Text = "Detailed Table Information"; oPara4.Format.SpaceAfter = 6; oPara4.Range.InsertParagraphAfter(); #region Setting Header foreach (Word.Section section in oDoc.Sections) { Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage); headerRange.Text = "Govt Portal \t \t Protech Solutions \nPDM"; } #endregion #region Setting Footer foreach (Word.Section wordSection in oDoc.Sections) { Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; footerRange.Text = date.ToString("MMMM dd, yyyy"); } #endregion //Get Table Meta Data foreach (var t in sortedTableData) { statement = Constatnts.statement2; List <string> primaryKeysList = new List <string>(); //Get Primary Key List #region Get Primary Key List for Each Table using (SqlConnection con1 = new SqlConnection(cs)) { string s = Constatnts.statement3; SqlCommand cmd = new SqlCommand(s, con1); con1.Open(); SqlDataReader reader; cmd.Parameters.AddWithValue("@As_Table_NAME", t.TableName); reader = cmd.ExecuteReader(); while (reader.Read()) { string colName = reader["COLUMN_NAME"].ToString(); primaryKeysList.Add(colName); } } #endregion using (SqlConnection con = new SqlConnection(cs)) { SqlCommand cmd = new SqlCommand(statement, con); con.Open(); SqlDataReader reader; cmd.Parameters.AddWithValue("@As_Table_NAME", t.TableName); reader = cmd.ExecuteReader(); List <TableMetaData> listOfTMD = new List <TableMetaData>(); while (reader.Read()) { TableMetaData tmd = new TableMetaData(); tmd.TableName = t.TableName; tmd.ColumnName = reader["COLUMN_NAME"].ToString(); tmd.Id = reader["ORDINAL_POSITION"].ToString(); tmd.PK = reader["IS_NULLABLE"].ToString(); tmd.DataType = reader["DATA_TYPE"].ToString(); tmd.Length = reader["LENGTH"].ToString(); tmd.Precision = reader["PRECISION"].ToString(); tmd.Scale = reader["SCALE"].ToString(); tmd.Identity = reader["IsIdentity"].ToString(); listOfTMD.Add(tmd); } //Add para to show table Name and Synonym Name Word.Paragraph oPara3; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara3 = oDoc.Content.Paragraphs.Add(ref oRng); oPara3.Range.ParagraphFormat.SpaceAfter = 6; oPara3.Range.Text = $@"Table Name: {t.TableName} Synonym Name: {t.SynonymName}"; wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, listOfTMD.Count + 1, 8, ref oMissing, ref oMissing); oTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; oTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; oTable.Range.ParagraphFormat.SpaceAfter = 6; oTable.Range.Font.Bold = 1; oTable.Cell(1, 1).Range.Text = "ColumnName"; oTable.Cell(1, 2).Range.Text = "Id"; oTable.Cell(1, 3).Range.Text = "PK"; oTable.Cell(1, 4).Range.Text = "DataType"; oTable.Cell(1, 5).Range.Text = "Length"; oTable.Cell(1, 6).Range.Text = "Precision"; oTable.Cell(1, 7).Range.Text = "Scale"; oTable.Cell(1, 8).Range.Text = "IsIdentity"; oTable.Cell(1, 1).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray40; oTable.Cell(1, 2).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray40; oTable.Cell(1, 3).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray40; oTable.Cell(1, 4).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray40; oTable.Cell(1, 5).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray40; oTable.Cell(1, 6).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray40; oTable.Cell(1, 7).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray40; oTable.Cell(1, 8).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray40; oTable.Rows[1].Range.Font.Bold = 1; oTable.Columns[1].PreferredWidth = oWord.InchesToPoints(2.4f); oTable.Columns[2].PreferredWidth = oWord.InchesToPoints(0.35f); oTable.Columns[3].PreferredWidth = oWord.InchesToPoints(0.42f); oTable.Columns[4].PreferredWidth = oWord.InchesToPoints(0.9f); oTable.Columns[5].PreferredWidth = oWord.InchesToPoints(0.7f); oTable.Columns[6].PreferredWidth = oWord.InchesToPoints(0.75f); oTable.Columns[7].PreferredWidth = oWord.InchesToPoints(0.7f); oTable.Columns[8].PreferredWidth = oWord.InchesToPoints(0.75f); wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.InsertParagraphAfter(); wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.InsertParagraphAfter(); oTable.Range.Font.Bold = 0; int q = 0; for (r = 2; r <= listOfTMD.Count + 1; r++) { oTable.Cell(r, 1).Range.Text = listOfTMD[q].ColumnName; oTable.Cell(r, 2).Range.Text = listOfTMD[q].Id; if (primaryKeysList.Contains(listOfTMD[q].ColumnName)) { oTable.Cell(r, 3).Range.Text = "1"; } else { oTable.Cell(r, 3).Range.Text = "0"; } oTable.Cell(r, 4).Range.Text = listOfTMD[q].DataType; oTable.Cell(r, 5).Range.Text = listOfTMD[q].Length; oTable.Cell(r, 6).Range.Text = listOfTMD[q].Precision; oTable.Cell(r, 7).Range.Text = listOfTMD[q].Scale; oTable.Cell(r, 8).Range.Text = listOfTMD[q].Identity; q++; } oTable.Rows[1].Range.Font.Bold = 1; } } string fileName = textBox_OutputPath.Text == "" ? @"C:" : textBox_OutputPath.Text; fileName = textBox_OutputPath.Text + @"\PDM"; oDoc.SaveAs2(fileName); this.Close(); }
public void Otchet_To_Word(DataGridView dataGridViewMain, string filename)// Метод экспорта в Word { Word.Document oDoc = new Word.Document(); oDoc.Application.Visible = true; //ориентация страницы oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientPortrait; // Стиль текста. object start = 0, end = 0; Word.Range rng = oDoc.Range(ref start, ref end); rng.InsertBefore("Отчет");//Заголовок rng.Font.Name = "Times New Roman"; rng.Font.Size = 12; rng.InsertParagraphAfter(); rng.InsertParagraphAfter(); rng.SetRange(rng.End, rng.End); oDoc.Content.ParagraphFormat.LeftIndent = oDoc.Content.Application.CentimetersToPoints(0); // отступ слева oDoc.Paragraphs.Format.FirstLineIndent = 0; //Отступ первой строки oDoc.Paragraphs.Format.LineSpacing = 8; //межстрочный интервал в первом абзаце.(высота строк) oDoc.Paragraphs.Format.SpaceBefore = 3; //межстрочный интервал перед первым абзацем. oDoc.Paragraphs.Format.SpaceAfter = 1; //межстрочный интервал после первого абзаца. if (dataGridViewMain.Rows.Count != 0) { //удаление столбца //this.dataGridView1.Columns.RemoveAt(4);//дата записи string kol_vo = Convert.ToString(textBoxAmount.Text); //кол-во string sum = Convert.ToString(textBoxSumm.Text); //сумма DateTime month = Convert.ToDateTime(dataGridViewMain.Rows[0].Cells[4].Value); int RowCount = dataGridViewMain.Rows.Count; int ColumnCount = dataGridViewMain.Columns.Count - 1;// столбцы в гриде (-5 последних) Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1]; // добавить строки int r = 0; for (int c = 0; c <= ColumnCount - 1; c++) { for (r = 0; r <= RowCount - 1; r++) { DataArray[r + 1, c] = dataGridViewMain.Rows[r].Cells[c].Value;// +1 это первая строка в таблице над заголовком } //Конец цикла строки } //конец петли колонки //Добавление текста в документ oDoc.Content.SetRange(0, 0);// для текстовых строк oDoc.Content.Text = " Кол-во: " + kol_vo + " Сумма: " + sum + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + "Начальник транспортного отдела " + Environment.NewLine + Environment.NewLine + "______________________________" + Environment.NewLine; dynamic oRange = oDoc.Content.Application.Selection.Range; string oTemp = ""; for (r = 0; r <= RowCount - 1; r++) { for (int c = 0; c <= ColumnCount - 1; c++) { oTemp = oTemp + DataArray[r, c] + "\t"; } } //формат таблицы oRange.Text = oTemp; object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs; object ApplyBorders = true; object AutoFit = true; object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent; oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount, Type.Missing, Type.Missing, ref ApplyBorders, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing); oRange.Select(); oDoc.Application.Selection.Tables[1].Select(); oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0; oDoc.Application.Selection.Tables[1].Rows.Alignment = 0; oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.InsertRowsAbove(1); oDoc.Application.Selection.Tables[1].Rows[1].Select(); //стиль строки заголовка oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1; oDoc.Application.Selection.Tables[1].Rows[2].Range.Bold = 1; oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Times New Roman"; oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 9; //добавить строку заголовка вручную for (int c = 0; c <= ColumnCount - 1; c++) { oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = ""; oDoc.Application.Selection.Tables[1].Cell(2, c + 1).Range.Text = dataGridViewMain.Columns[c].HeaderText; } //стиль таблицы oDoc.Application.Selection.Tables[1].Columns[3].Delete(); //Удалить столбец oDoc.Application.Selection.Tables[1].Columns[3].Delete(); //Удалить столбец oDoc.Application.Selection.Tables[1].Columns[4].Delete(); //Удалить столбец oDoc.Application.Selection.Tables[1].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //Выравнивание текста в таблице по центру oDoc.Application.Selection.Tables[1].Rows.Borders.Enable = 1; //borders oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; oDoc.Application.Selection.Tables[1].Columns[1].Width = 120; //ширина столбца oDoc.Application.Selection.Tables[1].Columns[2].Width = 120; //ширина столбца oDoc.Application.Selection.Tables[1].Columns[3].Width = 80; //ширина столбца oDoc.Application.Selection.Tables[1].Columns[4].Width = 80; //ширина столбца oDoc.Application.Selection.Tables[1].Columns[5].Width = 120; //ширина столбца //oDoc.Application.Selection.Tables[1].Columns[6].Width = 60;//ширина столбца //oDoc.Application.Selection.Tables[1].Columns[7].Width = 80;//ширина столбца oDoc.Application.Selection.Tables[1].LeftPadding = 1; //отступ с лева полей ячеек oDoc.Application.Selection.Tables[1].RightPadding = 1; //отступ с права полей ячеек oDoc.Application.Selection.Tables[1].Rows.LeftIndent = -30; //Установка отступа слева //oDoc.Application.Selection.Tables[1].Cell(1, 2).Range.Text = "текст в ячейке"; //oDoc.Application.Selection.Tables[1].Cell(1, 2).Merge(oDoc.Application.Selection.Tables[1].Cell(1, 4));//Объединение //текст заголовка foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections) { // Верхний колонтитул DateTime Now = DateTime.Now; Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range; headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage); section.PageSetup.DifferentFirstPageHeaderFooter = -1;//Включить особый колонтитул headerRange.Text = Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + "Сводный отчет" + Environment.NewLine + "по ремонту и обслуживанию автомобилей" + Environment.NewLine + "ГП Службы специальной связи" + Environment.NewLine + "с " + Convert.ToString(dateTimePickerStart.Value.ToString("dd.MM.yyyy")) + " по " + Convert.ToString(dateTimePickerEnd.Value.ToString("dd.MM.yyyy")) + Environment.NewLine; headerRange.Font.Size = 14; headerRange.Font.Name = "Times New Roman"; headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; // Нижний колонтитул Word.Range footerRange = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footerRange.Fields.Add(footerRange, Word.WdFieldType.wdFieldPage); footerRange.Text = "Служба специальной связи " + Convert.ToString(Now.ToString("dd.MM.yyyy")); footerRange.Font.Size = 9; footerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; } //сохранить файл oDoc.SaveAs(filename); } }
public void XuatRaFileWord(DataGridView DGV, string filename) { if (DGV.Rows.Count != 0) { int RowCount = DGV.Rows.Count; int ColumnCount = DGV.Columns.Count; Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1]; //add rows int r = 0; for (int c = 0; c <= ColumnCount - 1; c++) { for (r = 0; r <= RowCount - 1; r++) { DataArray[r, c] = DGV.Rows[r].Cells[c].Value; } //end row loop } //end column loop Word.Document oDoc = new Word.Document(); oDoc.Application.Visible = true; //page orintation oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape; dynamic oRange = oDoc.Content.Application.Selection.Range; string oTemp = ""; for (r = 0; r <= RowCount - 1; r++) { for (int c = 0; c <= ColumnCount - 1; c++) { oTemp = oTemp + DataArray[r, c] + "\t"; } } //table format oRange.Text = oTemp; object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs; object ApplyBorders = true; object AutoFit = true; object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent; oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount, Type.Missing, Type.Missing, ref ApplyBorders, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing); oRange.Select(); oDoc.Application.Selection.Tables[1].Select(); oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0; oDoc.Application.Selection.Tables[1].Rows.Alignment = 0; oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.InsertRowsAbove(1); oDoc.Application.Selection.Tables[1].Rows[1].Select(); //header row style oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1; oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma"; oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14; //add header row manually for (int c = 0; c <= ColumnCount - 1; c++) { oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText; } //table style oDoc.Application.Selection.Tables[1].set_Style("Table Grid 3"); oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //header text foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections) { Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage); headerRange.Text = "Tổng tiền của " + Tenban; headerRange.Font.Size = 16; headerRange.Font.Bold = 1; headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } // insert a line text into word Word.Paragraph p = oDoc.Paragraphs.Add(); Word.Range tongtien = p.Range; tongtien.Text = "Tổng tiền: " + txttongtien.Text + " VNĐ"; // change align of text tongtien.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; tongtien.InsertParagraphAfter(); // insert datetime Word.Paragraph p1 = oDoc.Paragraphs.Add(); Word.Range thoigianlap = p1.Range; thoigianlap.Text = DateTime.Now.ToString(); thoigianlap.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; thoigianlap.InsertParagraphAfter(); //save the file oDoc.SaveAs(filename); } }
public static void AutomateWord() { object missing = Type.Missing; object notTrue = false; Word.Application oWord = null; Word.Documents oDocs = null; Word.Document oDoc = null; Word.Paragraphs oParas = null; Word.Paragraph oPara = null; Word.Range oParaRng = null; Word.Font oFont = null; try { // Create an instance of Microsoft Word and make it invisible. oWord = new Word.Application(); oWord.Visible = false; Console.WriteLine("Word.Application is started"); // Create a new Document and add it to document collection. oDoc = oWord.Documents.Add(ref missing, ref missing, ref missing, ref missing); Console.WriteLine("A new document is created"); // Insert a paragraph. Console.WriteLine("Insert a paragraph"); oParas = oDoc.Paragraphs; oPara = oParas.Add(ref missing); oParaRng = oPara.Range; oParaRng.Text = "Heading 1"; oFont = oParaRng.Font; oFont.Bold = 1; oParaRng.InsertParagraphAfter(); // Save the document as a docx file and close it. Console.WriteLine("Save and close the document"); object fileName = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location) + "\\Sample1.docx"; object fileFormat = Word.WdSaveFormat.wdFormatXMLDocument; // Saves the document with a new name or format. // Some of the arguments for this method correspond to // the options in the Save As dialog box. // For details,please refer to // :http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.document.saveas(VS.80).aspx oDoc.SaveAs(ref fileName, ref fileFormat, 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); ((Word._Document)oDoc).Close(ref missing, ref missing, ref missing); // Quit the Word application. Console.WriteLine("Quit the Word application"); ((Word._Application)oWord).Quit(ref notTrue, ref missing, ref missing); } catch (Exception ex) { Console.WriteLine("Solution1.AutomateWord throws the error: {0}", ex.Message); } finally { // Clean up the unmanaged Word COM resources by explicitly // calling Marshal.FinalReleaseComObject on all accessor objects. // See http://support.microsoft.com/kb/317109. if (oFont != null) { Marshal.FinalReleaseComObject(oFont); oFont = null; } if (oParaRng != null) { Marshal.FinalReleaseComObject(oParaRng); oParaRng = null; } if (oPara != null) { Marshal.FinalReleaseComObject(oPara); oPara = null; } if (oParas != null) { Marshal.FinalReleaseComObject(oParas); oParas = null; } if (oDoc != null) { Marshal.FinalReleaseComObject(oDoc); oDoc = null; } if (oDocs != null) { Marshal.FinalReleaseComObject(oDocs); oDocs = null; } if (oWord != null) { Marshal.FinalReleaseComObject(oWord); oWord = null; } } }
private void GenerateDocumentButton_Click(object sender, RoutedEventArgs e) { object objMissing = System.Reflection.Missing.Value; object objEndOfDocFlag = "\\endofdoc"; Word.Application objWord = new Word.Application { Visible = true }; Word.Document objDoc = objWord.Documents.Add(ref objMissing, ref objMissing, ref objMissing, ref objMissing); // Перший параграф, форматування Word.Range par1 = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; par1.Font.Size = 14; par1.Font.Name = "Times New Roman"; par1.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify; par1.ParagraphFormat.LineSpacing = 18; par1.ParagraphFormat.FirstLineIndent = objWord.InchesToPoints((float)0.0); par1.ParagraphFormat.SpaceAfter = 0; par1.ParagraphFormat.SpaceBefore = 0; // Генерація вмісту par1.Text = "В.4.1. Розрахунок часу командира механізованої роти."; par1.InsertParagraphAfter(); // Другий параграф, форматування Word.Range par2 = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; par2.Font.Size = 14; par2.Font.Name = "Times New Roman"; par2.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify; par2.ParagraphFormat.LineSpacing = 18; par2.ParagraphFormat.FirstLineIndent = objWord.InchesToPoints((float)0.0); par2.ParagraphFormat.SpaceAfter = 0; par2.ParagraphFormat.SpaceBefore = 0; // Генерація вмісту par2.Text = "Час отримання завдання: " + textBox1.Text + "."; par2.InsertParagraphAfter(); // Третій параграф, форматування Word.Range par3 = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; par3.Font.Size = 14; par3.Font.Name = "Times New Roman"; par3.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify; par3.ParagraphFormat.LineSpacing = 18; par3.ParagraphFormat.FirstLineIndent = objWord.InchesToPoints((float)0.0); par3.ParagraphFormat.SpaceAfter = 0; par3.ParagraphFormat.SpaceBefore = 0; // Генерація вмісту par3.Text = "Час готовності: " + textBox2.Text + "."; par3.InsertParagraphAfter(); // Четвертий параграф, форматування Word.Range par4 = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; par4.Font.Size = 14; par4.Font.Name = "Times New Roman"; par4.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify; par4.ParagraphFormat.LineSpacing = 18; par4.ParagraphFormat.FirstLineIndent = objWord.InchesToPoints((float)0.0); par4.ParagraphFormat.SpaceAfter = 0; par4.ParagraphFormat.SpaceBefore = 0; // Генерація вмісту par4.Text = "Загальний час для підготовки підрозділів: " + textBox3.Text + "."; par4.InsertParagraphAfter(); // П'ятий параграф, форматування Word.Range par5 = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; par5.Font.Size = 14; par5.Font.Name = "Times New Roman"; par5.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify; par5.ParagraphFormat.LineSpacing = 18; par5.ParagraphFormat.FirstLineIndent = objWord.InchesToPoints((float)0.0); par5.ParagraphFormat.SpaceAfter = 0; par5.ParagraphFormat.SpaceBefore = 0; // Генерація вмісту par5.Text = "Кількість світлого часу доби: " + textBox4.Text + "."; par5.InsertParagraphAfter(); // Шостий параграф, форматування Word.Range par6 = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; par6.Font.Size = 14; par6.Font.Name = "Times New Roman"; par6.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify; par6.ParagraphFormat.LineSpacing = 18; par6.ParagraphFormat.FirstLineIndent = objWord.InchesToPoints((float)0.0); par6.ParagraphFormat.SpaceAfter = 0; par6.ParagraphFormat.SpaceBefore = 0; // Генерація вмісту par6.Text = "Кількість темного часу доби: " + textBox5.Text + "."; par6.InsertParagraphAfter(); // Таблиця, форматування Word.Range par7 = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; Word.Table tableObj; tableObj = objDoc.Tables.Add(par7, 18, 4, ref objMissing, ref objMissing); tableObj.Range.Font.Name = "Times New Roman"; tableObj.Range.Font.Size = 12; tableObj.Range.ParagraphFormat.LineSpacing = 12; tableObj.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; tableObj.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; tableObj.Cell(1, 1).Merge(tableObj.Cell(2, 1)); tableObj.Cell(1, 2).Merge(tableObj.Cell(2, 2)); tableObj.Cell(1, 3).Merge(tableObj.Cell(1, 4)); tableObj.Cell(1, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; tableObj.Cell(1, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalTop; tableObj.Cell(1, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; tableObj.Cell(1, 2).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalTop; tableObj.Cell(1, 3).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; tableObj.Cell(1, 3).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalTop; tableObj.Cell(2, 3).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; tableObj.Cell(2, 3).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalTop; tableObj.Cell(2, 4).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; tableObj.Cell(2, 4).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalTop; for (int i = 3; i <= 18; i++) { tableObj.Cell(i, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; tableObj.Cell(i, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalTop; } for (int i = 3; i <= 18; i++) { for (int j = 2; j <= 4; j++) { tableObj.Cell(i, j).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; tableObj.Cell(i, j).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalTop; } } tableObj.Cell(1, 3).Range.ParagraphFormat.SpaceAfter = 8; // Таблиця, генерація вмісту tableObj.Cell(1, 1).Range.Text = "Заходи, що проводяться"; tableObj.Cell(1, 2).Range.Text = "Загальна кількість часу (хв)"; tableObj.Cell(1, 3).Range.Text = "Час роботи"; tableObj.Cell(2, 3).Range.Text = "Початок\n(час, дата)"; tableObj.Cell(2, 4).Range.Text = "Кінець\n(час, дата)"; tableObj.Cell(3, 1).Range.Text = "З’ясування завдання"; tableObj.Cell(3, 2).Range.Text = textBox6.Text; tableObj.Cell(3, 3).Range.Text = textBox7.Text; tableObj.Cell(3, 4).Range.Text = textBox8.Text; tableObj.Cell(4, 1).Range.Text = "Визначення заходів, які необхідно провести негайно для підготовки роти до бою"; tableObj.Cell(4, 2).Range.Text = textBox9.Text; tableObj.Cell(4, 3).Range.Text = textBox10.Text; tableObj.Cell(4, 4).Range.Text = textBox11.Text; tableObj.Cell(5, 1).Range.Text = "Відпрацювання розрахунку часу"; tableObj.Cell(5, 2).Range.Text = textBox12.Text; tableObj.Cell(5, 3).Range.Text = textBox13.Text; tableObj.Cell(5, 4).Range.Text = textBox14.Text; tableObj.Cell(6, 1).Range.Text = "Оцінка обстановки"; tableObj.Cell(6, 2).Range.Text = textBox15.Text; tableObj.Cell(6, 3).Range.Text = textBox16.Text; tableObj.Cell(6, 4).Range.Text = textBox17.Text; tableObj.Cell(7, 1).Range.Text = "Прийняття рішення"; tableObj.Cell(7, 2).Range.Text = textBox18.Text; tableObj.Cell(7, 3).Range.Text = textBox19.Text; tableObj.Cell(7, 4).Range.Text = textBox20.Text; tableObj.Cell(8, 1).Range.Text = "Доповідь рішення старшому командиру"; tableObj.Cell(8, 2).Range.Text = textBox21.Text; tableObj.Cell(8, 3).Range.Text = textBox22.Text; tableObj.Cell(8, 4).Range.Text = textBox23.Text; tableObj.Cell(9, 1).Range.Text = "Проведення рекогносцировки"; tableObj.Cell(9, 2).Range.Text = textBox24.Text; tableObj.Cell(9, 3).Range.Text = textBox25.Text; tableObj.Cell(9, 4).Range.Text = textBox26.Text; tableObj.Cell(10, 1).Range.Text = "Віддання бойового наказу"; tableObj.Cell(10, 2).Range.Text = textBox27.Text; tableObj.Cell(10, 3).Range.Text = textBox28.Text; tableObj.Cell(10, 4).Range.Text = textBox29.Text; tableObj.Cell(11, 1).Range.Text = "Організація взаємодії і системи вогню та віддання вказівок, щодо всебічного забезпечення"; tableObj.Cell(11, 2).Range.Text = textBox30.Text; tableObj.Cell(11, 3).Range.Text = textBox31.Text; tableObj.Cell(11, 4).Range.Text = textBox32.Text; tableObj.Cell(12, 1).Range.Text = "Зайняття ротного опорного пункту"; tableObj.Cell(12, 2).Range.Text = textBox33.Text; tableObj.Cell(12, 3).Range.Text = textBox34.Text; tableObj.Cell(12, 4).Range.Text = textBox35.Text; tableObj.Cell(13, 1).Range.Text = "Доповідь командиру батальйону про готовність системи вогню"; tableObj.Cell(13, 2).Range.Text = textBox36.Text; tableObj.Cell(13, 3).Range.Text = textBox37.Text; tableObj.Cell(13, 4).Range.Text = textBox38.Text; tableObj.Cell(14, 1).Range.Text = "Виконання робіт інженерного обладнання РОП 1 черги"; tableObj.Cell(14, 2).Range.Text = textBox39.Text; tableObj.Cell(14, 3).Range.Text = textBox40.Text; tableObj.Cell(14, 4).Range.Text = textBox41.Text; tableObj.Cell(15, 1).Range.Text = "Виконання робіт інженерного обладнання РОП 2 черги"; tableObj.Cell(15, 2).Range.Text = textBox42.Text; tableObj.Cell(15, 3).Range.Text = textBox43.Text; tableObj.Cell(15, 4).Range.Text = textBox44.Text; tableObj.Cell(16, 1).Range.Text = "Контроль та допомога командирам підрозділів в організації оборони."; tableObj.Cell(16, 2).Range.Text = textBox45.Text; tableObj.Cell(16, 3).Range.Text = textBox46.Text; tableObj.Cell(16, 4).Range.Text = textBox47.Text; tableObj.Cell(17, 1).Range.Text = "Прийняття доповіді командирів підрозділів про готовність оборони"; tableObj.Cell(17, 2).Range.Text = textBox48.Text; tableObj.Cell(17, 3).Range.Text = textBox49.Text; tableObj.Cell(17, 4).Range.Text = textBox50.Text; tableObj.Cell(18, 1).Range.Text = "Доповідь командиру батальйону про готовність оборони"; tableObj.Cell(18, 2).Range.Text = textBox51.Text; tableObj.Cell(18, 3).Range.Text = textBox52.Text; tableObj.Cell(18, 4).Range.Text = textBox53.Text; par7.InsertParagraphAfter(); try { Directory.CreateDirectory(Constant.RootToSaveGenerated); objDoc.SaveAs($"{Constant.RootToSaveGenerated}Form 4_1 {Constant.Date}"); string path = objDoc.FullName; var dialog = new DialogPrintDocument("Підтвердити друк?"); dialog.ShowDialog(); if (dialog.Cancelled != true) { objDoc.PrintOut(); } objDoc.Close(); objWord.Quit(); var order = orderService.AddOrder(path, hashService.GetHash()); if (order != null) { CustomMessageBox messageBox = new CustomMessageBox("Донесення занесено до бази даних!"); messageBox.ShowDialog(); } else { CustomMessageBox messageBox = new CustomMessageBox("Сталася помилка! Донесення не занесено до бази даних!"); messageBox.ShowDialog(); } } catch (Exception ex) { CustomMessageBox messageBox = new CustomMessageBox(ex.Message); messageBox.ShowDialog(); } }
public void Export_Data_To_Word2(DataGridView dataGridView2, string filename)//Обработчик Word МБП { Word.Document oDoc = new Word.Document(); oDoc.Application.Visible = true; //ориентация страницы oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape; // Стиль текста. object start = 0, end = 0; Word.Range rng = oDoc.Range(ref start, ref end); rng.InsertBefore("Заголовок");//Заголовок rng.Font.Name = "Times New Roman"; rng.Font.Size = 9; rng.InsertParagraphAfter(); rng.InsertParagraphAfter(); rng.SetRange(rng.End, rng.End); oDoc.Content.ParagraphFormat.LeftIndent = oDoc.Content.Application.CentimetersToPoints(0); // отступ слева if (dataGridView2.Rows.Count != 0) { int RowCount = dataGridView2.Rows.Count; int ColumnCount = dataGridView2.Columns.Count; Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1]; // добавить строки int r = 0; for (int c = 0; c <= ColumnCount - 1; c++) { for (r = 0; r <= RowCount - 1; r++) { DataArray[r, c] = dataGridView2.Rows[r].Cells[c].Value; } //Конец цикла строки } //конец петли колонки //Добавление текста в документ string saldo_nachalo = Convert.ToString(textBox8.Text);//Сальдо начало string saldo_konec = Convert.ToString(textBox9.Text);//Сальдо конец oDoc.Content.SetRange(0, 0); oDoc.Content.Text = "Сальдо на начало: " + saldo_nachalo + " Сальдо на конец: " + saldo_konec + Environment.NewLine + Environment.NewLine + "Выполнил__________________" + " " + "Принял_____________________" + Environment.NewLine; dynamic oRange = oDoc.Content.Application.Selection.Range; string oTemp = ""; for (r = 0; r <= RowCount - 1; r++) { for (int c = 0; c <= ColumnCount - 1; c++) { oTemp = oTemp + DataArray[r, c] + "\t"; } } //формат таблицы oRange.Text = oTemp; object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs; object ApplyBorders = true; object AutoFit = true; object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent; oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount, Type.Missing, Type.Missing, ref ApplyBorders, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing); oRange.Select(); oDoc.Application.Selection.Tables[1].Select(); oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0; oDoc.Application.Selection.Tables[1].Rows.Alignment = 0; oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.InsertRowsAbove(1); oDoc.Application.Selection.Tables[1].Rows[1].Select(); //заголовка стиль строки oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1; oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Times New Roman"; oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 9; //добавить строку заголовка вручную for (int c = 0; c <= ColumnCount - 1; c++) { oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = dataGridView2.Columns[c].HeaderText; } //стиль таблицы oDoc.Application.Selection.Tables[1].Rows.Borders.Enable = 1;//borders oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //текст заголовка foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections) {//Верхний колонтитул DateTime Now = DateTime.Now; Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range; headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage); section.PageSetup.DifferentFirstPageHeaderFooter = -1;//Включить особый колонтитул headerRange.Text = "Отчет №_"; headerRange.Font.Size = 12; headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //Нижний колонтитул Word.Range footerRange = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range; footerRange.Fields.Add(footerRange, Word.WdFieldType.wdFieldPage); footerRange.Text = "ГП Служба специальной связи " + Convert.ToString(Now.ToString("dd:MM:yyyy")); footerRange.Font.Size = 9; footerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; } //сохранить файл oDoc.SaveAs(filename); } }
public static void AutomateWord() { object missing = Type.Missing; object notTrue = false; Word.Application oWord = null; Word.Documents oDocs = null; Word.Document oDoc = null; Word.Paragraphs oParas = null; Word.Paragraph oPara = null; Word.Range oParaRng = null; Word.Font oFont = null; try { // 创建一个Microsoft Word实例并令其不可见 oWord = new Word.Application(); oWord.Visible = false; Console.WriteLine("Word.Application is started"); // 创建一个新的文档 oDocs = oWord.Documents; oDoc = oDocs.Add(ref missing, ref missing, ref missing, ref missing); Console.WriteLine("A new document is created"); // 插入段落 Console.WriteLine("Insert a paragraph"); oParas = oDoc.Paragraphs; oPara = oParas.Add(ref missing); oParaRng = oPara.Range; oParaRng.Text = "Heading 1"; oFont = oParaRng.Font; oFont.Bold = 1; oParaRng.InsertParagraphAfter(); // 将文档保存为.docx文件并关闭 Console.WriteLine("Save and close the document"); object fileName = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location) + "\\Sample1.docx"; object fileFormat = Word.WdSaveFormat.wdFormatXMLDocument; oDoc.SaveAs(ref fileName, ref fileFormat, 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); ((Word._Document)oDoc).Close(ref missing, ref missing, ref missing); // 退出Word应用程序 Console.WriteLine("Quit the Word application"); ((Word._Application)oWord).Quit(ref notTrue, ref missing, ref missing); } catch (Exception ex) { Console.WriteLine("Solution1.AutomateWord throws the error: {0}", ex.Message); } finally { // 通过在所有访问对象上显示调用Marshal.FinalReleaseComObject方法 // 释放非托管Word COM资源 // 见 http://support.microsoft.com/kb/317109. if (oFont != null) { Marshal.FinalReleaseComObject(oFont); oFont = null; } if (oParaRng != null) { Marshal.FinalReleaseComObject(oParaRng); oParaRng = null; } if (oPara != null) { Marshal.FinalReleaseComObject(oPara); oPara = null; } if (oParas != null) { Marshal.FinalReleaseComObject(oParas); oParas = null; } if (oDoc != null) { Marshal.FinalReleaseComObject(oDoc); oDoc = null; } if (oDocs != null) { Marshal.FinalReleaseComObject(oDocs); oDocs = null; } if (oWord != null) { Marshal.FinalReleaseComObject(oWord); oWord = null; } } }
public static void foo() { object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; Word._Application oWord = new Word.Application(); Word._Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); oWord.Visible = true; Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; //Insert a chart. Word.InlineShape oShape; object oClassType = "MSGraph.Chart.8"; wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //Demonstrate use of late bound oChart and oChartApp objects to //manipulate the chart object with MSGraph. object oChart; object oChartApp; oChart = oShape.OLEFormat.Object; oChartApp = oChart.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, oChart, null); //Change the chart type to Line. object[] Parameters = new Object[1]; Parameters[0] = 2; //xlLine = 4 oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty, null, oChart, Parameters); //Update the chart image and quit MSGraph. oChartApp.GetType().InvokeMember("Update", BindingFlags.InvokeMethod, null, oChartApp, null); oChartApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, oChartApp, null); //... If desired, you can proceed from here using the Microsoft Graph //Object model on the oChart and oChartApp objects to make additional //changes to the chart. //Set the width of the chart. oShape.Width = oWord.InchesToPoints(6.25f); oShape.Height = oWord.InchesToPoints(3.57f); //Add text after the chart. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("THE END."); }
private void CreateDocument() { if (cboAssRef.SelectedItem == null) { Cursor.Current = Cursors.Default; MessageBox.Show("Please select an Assyst Reference.", "Assyst Case", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } string strAssRef = ""; if (this.Text == "DTaS APPendix - Add Assyst Case") { strAssRef = this.txtAssRef.Text; //Textbox Assyst Ref } else { strAssRef = this.cboAssRef.SelectedValue.ToString(); //Combobox Ass Ref } object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ try { //Start Word and create a new document. Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); //Insert a paragraph at the beginning of the document. Word.Paragraph oPara1; oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Text = "Assyst Reference: " + strAssRef; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 6; //6 pt spacing after paragraph. oPara1.Range.InsertParagraphAfter(); Word.Range wrdRng = oDoc.Range(0); wrdRng.Font.Bold = 0; wrdRng.ParagraphFormat.SpaceAfter = 6; if (cboBDAppNo.SelectedItem == null) { wrdRng.InsertAfter("BDApp Number: "); } else { wrdRng.InsertAfter("BDApp Number: " + cboBDAppNo.Text); } wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("BDApp Name: " + txtBDAppName.Text); wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("Date Opened: " + txtDateOpened.Text); wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("SLA Target: " + txtSLATarget.Text); wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("Summary: " + txtSummary.Text); wrdRng.InsertParagraphAfter(); if (cboAssignDev.SelectedItem == null) { wrdRng.InsertAfter("Assigned to Developer: "); } else { wrdRng.InsertAfter("Assigned to Developer: " + cboAssignDev.Text); } wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("Acknowledgement Email Sent: " + txtEmailSent.Text); wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("Email Chased: " + txtEmailChased.Text); wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("Notes: " + txtNotes.Text); wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("Next Action Date: " + txtNAD.Text); wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("Next Action: " + txtNA.Text); wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("Date Resolved: " + txtDateResolved.Text); wrdRng.InsertParagraphAfter(); if (cboFix.SelectedItem == null) { wrdRng.InsertAfter("Fix Applied: "); } else { wrdRng.InsertAfter("Fix Applied: " + cboFix.Text); } wrdRng.InsertParagraphAfter(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private static void AddMarkingHeaderToDocument(ProtectiveMarking marking, Word.Document document) { Debug.WriteLine("PspfMarkingsAddIn: AddMarkingHeaderToDocument"); Debug.WriteLine("=============================================================================="); Word.Range range = null; Word.Font font = null; Word.ParagraphFormat format = null; try { object start = 0; object end = 0; // Move to start range = document.Range(ref start, ref end); // Insert Paragraph break range.InsertParagraphAfter(); Marshal.ReleaseComObject(range); // Move to start range = document.Range(ref start, ref end); range.Text = marking.MailBodyHeaderText; font = range.Font; if (!string.IsNullOrWhiteSpace(marking.MailBodyHeaderColour)) { var colorConverter = new ColorConverter(); var color = (Color)colorConverter.ConvertFromString(marking.MailBodyHeaderColour); font.Color = (Word.WdColor)(color.R + 0x100 * color.G + 0x10000 * color.B); } if (!string.IsNullOrWhiteSpace(marking.MailBodyHeaderSizePoints)) { font.Size = float.Parse(marking.MailBodyHeaderSizePoints); } if (!string.IsNullOrWhiteSpace(marking.MailBodyHeaderFont)) { font.Name = marking.MailBodyHeaderFont; } if (!string.IsNullOrWhiteSpace(marking.MailBodyHeaderAlign)) { format = range.ParagraphFormat; switch (marking.MailBodyHeaderAlign.ToLowerInvariant()) { case "center": case "centre": case "middle": format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; break; case "left": case "normal": format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; break; case "right": format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; break; default: Debug.WriteLine("Unexpected text alignment: " + marking.MailBodyHeaderAlign); break; } } // Force the edit to persist: document.Activate(); } finally { if (format != null) { Marshal.ReleaseComObject(format); } if (font != null) { Marshal.ReleaseComObject(font); } if (range != null) { Marshal.ReleaseComObject(range); } } }
public static string TestWord() { string report = "Chưa kiểm tra Word."; //kt word object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); //Insert a paragraph at the beginning of the document. Word.Paragraph oPara1; oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Text = "hello word "; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. oPara1.Range.InsertParagraphAfter(); //Insert a paragraph at the end of the document. Word.Paragraph oPara2; object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara2 = oDoc.Content.Paragraphs.Add(ref oRng); oPara2.Range.Text = "xin chao"; oPara2.Format.SpaceAfter = 6; oPara2.Range.InsertParagraphAfter(); //Insert another paragraph. Word.Paragraph oPara3; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara3 = oDoc.Content.Paragraphs.Add(ref oRng); oPara3.Range.Text = "Bây giờ đây là một bảng:"; oPara3.Range.Font.Bold = 0; oPara3.Format.SpaceAfter = 24; oPara3.Range.InsertParagraphAfter(); //Insert a 3 x 5 table, fill it with data, and make the first row //bold and italic. Word.Table oTable; Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; int r, c; string strText; for (r = 1; r <= 3; r++) { for (c = 1; c <= 5; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } } oTable.Rows[1].Range.Font.Bold = 1; oTable.Rows[1].Range.Font.Italic = 1; //Add some text after the table. Word.Paragraph oPara4; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara4 = oDoc.Content.Paragraphs.Add(ref oRng); oPara4.Range.InsertParagraphBefore(); oPara4.Range.Text = "bang khac:"; oPara4.Format.SpaceAfter = 24; oPara4.Range.InsertParagraphAfter(); //Insert a 5 x 2 table, fill it with data, and change the column widths. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; for (r = 1; r <= 5; r++) { for (c = 1; c <= 2; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } } oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2 oTable.Columns[2].Width = oWord.InchesToPoints(3); //Keep inserting text. When you get to 7 inches from top of the //document, insert a hard page break. object oPos; double dPos = oWord.InchesToPoints(7); oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter(); do { wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.ParagraphFormat.SpaceAfter = 6; wrdRng.InsertAfter("A line of text"); wrdRng.InsertParagraphAfter(); oPos = wrdRng.get_Information (Word.WdInformation.wdVerticalPositionRelativeToPage); }while (dPos >= Convert.ToDouble(oPos)); object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd; object oPageBreak = Word.WdBreakType.wdPageBreak; wrdRng.Collapse(ref oCollapseEnd); wrdRng.InsertBreak(ref oPageBreak); wrdRng.Collapse(ref oCollapseEnd); wrdRng.InsertAfter("bieu do:"); wrdRng.InsertParagraphAfter(); //Insert a chart. Word.InlineShape oShape; object oClassType = "MSGraph.Chart.8"; wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //Demonstrate use of late bound oChart and oChartApp objects to //manipulate the chart object with MSGraph. object oChart; object oChartApp; oChart = oShape.OLEFormat.Object; oChartApp = oChart.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, oChart, null); //Change the chart type to Line. object[] Parameters = new Object[1]; Parameters[0] = 4; //xlLine = 4 oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty, null, oChart, Parameters); //Update the chart image and quit MSGraph. oChartApp.GetType().InvokeMember("Update", BindingFlags.InvokeMethod, null, oChartApp, null); oChartApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, oChartApp, null); //... If desired, you can proceed from here using the Microsoft Graph //Object model on the oChart and oChartApp objects to make additional //changes to the chart. //Set the width of the chart. oShape.Width = oWord.InchesToPoints(6.25f); oShape.Height = oWord.InchesToPoints(3.57f); //Add text after the chart. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("THE END."); oDoc.SaveAs("MyFile.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, ref oMissing); oWord.Quit(); report += "\nĐÃ KIỂM TRA Word"; return(report); }
public int MyWord(string MessageSaveFile, bool SaveWordPage, bool WordVisible) { object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); if (WordVisible) { oWord.Visible = true; } else { oWord.Visible = false; } oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); //Insert a paragraph at the beginning of the document Word.Paragraph oPara1; oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Text = "Heading 1"; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. oPara1.Range.InsertParagraphAfter(); //Insert a paragraph at the end of the document. Word.Paragraph oPara2; object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara2 = oDoc.Content.Paragraphs.Add(ref oRng); oPara2.Range.Text = "Heading 2"; oPara2.Format.SpaceAfter = 6; oPara2.Range.InsertParagraphAfter(); //Insert another paragraph. Word.Paragraph oPara3; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara3 = oDoc.Content.Paragraphs.Add(ref oRng); oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:"; oPara3.Range.Font.Bold = 0; oPara3.Format.SpaceAfter = 24; oPara3.Range.InsertParagraphAfter(); //Insert a 3 x 5 table, fill it with data, and make the first row //bold and italic. Word.Table oTable; Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; int r, c; string strText; for (r = 1; r <= 3; r++) { for (c = 1; c <= 5; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } } oTable.Rows[1].Range.Font.Bold = 1; oTable.Rows[1].Range.Font.Italic = 1; //Add some text after the table. Word.Paragraph oPara4; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara4 = oDoc.Content.Paragraphs.Add(ref oRng); oPara4.Range.InsertParagraphBefore(); oPara4.Range.Text = "And here's another table:"; oPara4.Format.SpaceAfter = 24; oPara4.Range.InsertParagraphAfter(); //Insert a 5 x 2 table, fill it with data, and change the column widths. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; for (r = 1; r <= 5; r++) { for (c = 1; c <= 2; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } } oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2 oTable.Columns[2].Width = oWord.InchesToPoints(3); //Keep inserting text. When you get to 7 inches from top of the //document, insert a hard page break. object oPos; double dPos = oWord.InchesToPoints(7); oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter(); do { wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.ParagraphFormat.SpaceAfter = 6; wrdRng.InsertAfter("A line of text"); wrdRng.InsertParagraphAfter(); oPos = wrdRng.get_Information (Word.WdInformation.wdVerticalPositionRelativeToPage); }while (dPos >= Convert.ToDouble(oPos)); object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd; object oPageBreak = Word.WdBreakType.wdPageBreak; wrdRng.Collapse(ref oCollapseEnd); wrdRng.InsertBreak(ref oPageBreak); wrdRng.Collapse(ref oCollapseEnd); wrdRng.InsertAfter("We're now on page 2. Here's my chart:"); wrdRng.InsertParagraphAfter(); //Insert a chart. Word.InlineShape oShape; object oClassType = "MSGraph.Chart.8"; wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //Demonstrate use of late bound oChart and oChartApp objects to //manipulate the chart object with MSGraph. object oChart; object oChartApp; oChart = oShape.OLEFormat.Object; oChartApp = oChart.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, oChart, null); //Change the chart type to Line. object[] Parameters = new Object[1]; Parameters[0] = 4; //xlLine = 4 oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty, null, oChart, Parameters); //Update the chart image and quit MSGraph. oChartApp.GetType().InvokeMember("Update", BindingFlags.InvokeMethod, null, oChartApp, null); oChartApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, oChartApp, null); //... If desired, you can proceed from here using the Microsoft Graph //Object model on the oChart and oChartApp objects to make additional //changes to the chart. //Set the width of the chart. oShape.Width = oWord.InchesToPoints(6.25f); oShape.Height = oWord.InchesToPoints(3.57f); //Add text after the chart. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("THE END."); //Закрываем документ object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; if (SaveWordPage) { saveChanges = Word.WdSaveOptions.wdSaveChanges; } object originalFormat = Word.WdOriginalFormat.wdWordDocument; object routeDocument = Type.Missing; oWord.Quit(ref saveChanges, ref originalFormat, ref routeDocument); oWord = null; return(0); }