public static Word.Selection MoveToLabel(Word.Selection s, string label) { object oUnit = Word.WdUnits.wdStory; object oXtend = false; s.HomeKey(ref oUnit, ref oXtend); s.Find.ClearFormatting(); object findText = "$[" + label + "]"; object matchCase = false; object matchWholeWord = false; object matchWildCards = false; object matchSoundsLike = false; object matchAllForms = false; object forward = true; object wrap = Word.WdFindWrap.wdFindContinue; object format = false; object replaceWith = ""; object replace = Word.WdReplace.wdReplaceNone; object matchKashida = Type.Missing; object matchDiactrics = Type.Missing; object matchAliH = Type.Missing; object matchCOntrol = Type.Missing; s.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildCards, ref matchSoundsLike, ref matchAllForms, ref forward, ref wrap, ref format, ref replaceWith, ref replace, ref matchKashida, ref matchDiactrics, ref matchAliH, ref matchCOntrol); return(s); }
/// <summary> /// Word operation /// </summary> /// <param name="command"></param> /// <param name="sArg"></param> /// <param name="nArg1"></param> /// <param name="nArg2"></param> /// <param name="nArg3"></param> /// <param name="nArg4"></param> /// <returns></returns> public static string Call( string command, string sArg, int nArg1, int nArg2, int nArg3, int nArg4, bool bArg) { object missingObj = System.Reflection.Missing.Value; // missing object parameter if (SS.I.DebugFlags[5] != null) // dump out command for debug { ClientLog.Message("Call " + command + " " + sArg); } try // catch any Word exception { //****************************************************************************** if (Lex.Eq(command, "CreateObject")) // create the word object //****************************************************************************** { try { WdApp = new Microsoft.Office.Interop.Word.Application(); } catch (Exception ex) { return "Word failed to start"; } } //****************************************************************************** else if (Lex.Eq(command, "Quit")) { // quit application //****************************************************************************** //Microsoft.Office.Interop.Word.Application. WdApp.Quit(ref missingObj, ref missingObj, ref missingObj); // AutoWrap(DISPATCH_METHOD, NULL, WdApp, L"Quit", 0); } //****************************************************************************** else if (Lex.Eq(command, "Cells.SetWidth")) { //****************************************************************************** WdSel.Cells.SetWidth(nArg1, WdRulerStyle.wdAdjustNone); #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Cells", 0); WdTemp = result.pdispVal; SETLONG(Arg1,nArg1); // width in points SETLONG(Arg2,wdAdjustNone); // ruler style, required sArg AutoWrap(DISPATCH_METHOD, &result, WdTemp, L"Setwidth", 2, Arg2, Arg1); VariantClear(&Arg1); VariantClear(&Arg2); #endif } //****************************************************************************** else if (Lex.Eq(command, "DeleteObject")) { //****************************************************************************** WdSel = null; WdTable = null; WdTables = null; WdDoc = null; WdDocs = null; WdApp = null; #if false // Release references, must do lower to higher level... release_obj(WdTemp); release_obj(WdSel); release_obj(WdTable); release_obj(WdTables); release_obj(WdDoc); release_obj(WdDocs); release_obj(WdApp); #endif } //****************************************************************************** else if (Lex.Eq(command, "Close")) { //****************************************************************************** // excelobj.ActiveWorkbook.Close False ' no prompt for save ((_Document)WdDoc).Close(ref missingObj, ref missingObj, ref missingObj); // SETLONG(SaveChanges,wdSaveChanges); // don't prompt // AutoWrap(DISPATCH_METHOD, NULL, WdDoc, L"Close", 1, SaveChanges); // VariantClear(&SaveChanges); } //****************************************************************************** else if (Lex.Eq(command, "Documents.Add")) { // Add a new document //****************************************************************************** WdDocs = WdApp.Documents; WdDoc = WdDocs.Add(ref missingObj, ref missingObj, ref missingObj, ref missingObj); #if false release_obj(WdDocs); // Get active documents AutoWrap(DISPATCH_PROPERTYGET, &result, WdApp, L"Documents", 0); // Get Documents collection WdDocs = result.pdispVal; release_obj(WdDoc); // Add new document AutoWrap(DISPATCH_METHOD, &result, WdDocs, L"Add", 0); WdDoc = result.pdispVal; #endif if (WdDoc == null) return ("Error adding document"); UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "EndKey")) { //****************************************************************************** Object unit = nArg1; WdSel.HomeKey(ref unit, ref missingObj); // SETLONG(Arg,nArg1); // AutoWrap(DISPATCH_METHOD, &result, WdSel, L"HomeKey", 1, Arg); // VariantClear(&Arg); UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "Font.Name")) { //****************************************************************************** // WordObj.Selection.Font.Name = sArg WdSel.Font.Name = sArg; #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0); WdTemp = result.pdispVal; SETSTR(Arg,sArg); // set font name AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Name", 1, Arg); VariantClear(&Arg); #endif } //****************************************************************************** else if (Lex.Eq(command, "Font.Size")) { //****************************************************************************** // WordObj.Selection.Font.Size = sArg WdSel.Font.Size = nArg1; #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0); WdTemp = result.pdispVal; SETLONG(Arg,nArg1); // set font size AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Size", 1, Arg); VariantClear(&Arg); #endif } //****************************************************************************** else if (Lex.Eq(command, "Font.Bold")) //****************************************************************************** { if (bArg) WdSel.Font.Bold = -1; else WdSel.Font.Bold = 0; } //****************************************************************************** else if (Lex.Eq(command, "Font.Italic")) //****************************************************************************** { if (bArg) WdSel.Font.Italic = -1; else WdSel.Font.Italic = 0; } //****************************************************************************** else if (Lex.Eq(command, "Font.Subscript")) //****************************************************************************** { WdSel.Font.Subscript = nArg1; #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0); WdTemp = result.pdispVal; SETLONG(Arg,nArg1); // set font size AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Subscript", 1, Arg); VariantClear(&Arg); #endif } //****************************************************************************** else if (Lex.Eq(command, "Font.Superscript")) { //****************************************************************************** WdSel.Font.Superscript = nArg1; #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0); WdTemp = result.pdispVal; SETLONG(Arg,nArg1); // set font size AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Superscript", 1, Arg); VariantClear(&Arg); #endif } //****************************************************************************** else if (Lex.Eq(command, "SetDefaultCellStyle")) //****************************************************************************** { // Cell style (e.g. backcolor) automatically carries down do successive // rows and must be explicitly reset // int rgbBlack = 0; // if (WdSel.Font.Color != (Microsoft.Office.Interop.Word.WdColor)rgbBlack) // WdSel.Font.Color = (Microsoft.Office.Interop.Word.WdColor)rgbBlack; // int rgbWhite = 255 + 255 * 256 + 255 * 65536; // if (WdSel.Cells.Shading.BackgroundPatternColor != (Microsoft.Office.Interop.Word.WdColor)rgbWhite) // WdSel.Cells.Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)rgbWhite; if (WdSel.Font.Color != Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic) WdSel.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic; if (WdSel.Cells.Shading.BackgroundPatternColor != Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic) WdSel.Cells.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic; } //****************************************************************************** else if (Lex.Eq(command, "Font.Color")) //****************************************************************************** { Color c = Color.FromArgb(nArg1); int rgb = c.R + c.G * 256 + c.B * 65536; WdSel.Font.Color = (Microsoft.Office.Interop.Word.WdColor)rgb; } //****************************************************************************** else if (Lex.Eq(command, "BackColor")) //****************************************************************************** { Color c = Color.FromArgb(nArg1); int rgb = c.R + c.G * 256 + c.B * 65536; WdSel.Cells.Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)rgb; } //****************************************************************************** else if (Lex.Eq(command, "HomeKey")) { //****************************************************************************** Object unit = nArg1; WdSel.HomeKey(ref unit, ref missingObj); #if false SETLONG(Arg,nArg1); AutoWrap(DISPATCH_METHOD, &result, WdSel, L"HomeKey", 1, Arg); VariantClear(&Arg); #endif UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "InlineShapes.AddPicture")) { // insert image from file //****************************************************************************** InlineShape ils = WdSel.InlineShapes.AddPicture(sArg, ref missingObj, ref missingObj, ref missingObj); ils.Width = nArg1; ils.Height = nArg2; #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"InlineShapes", 0); WdTemp = result.pdispVal; SETSTR(Filename,sArg); // filename SETLONG(Width,nArg1); // in points SETLONG(Height,nArg2); AutoWrap(DISPATCH_METHOD, &result, WdTemp, L"AddPicture", 1, Filename); release_obj(WdTemp); WdTemp = result.pdispVal; // new shape object AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdTemp, L"Width", 1, Width); AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdTemp, L"Height", 1, Height); VariantClear(&Filename); VariantClear(&Width); VariantClear(&Height); #endif } //****************************************************************************** else if (Lex.Eq(command, "InsertBreak")) { //****************************************************************************** object type = nArg1; WdSel.InsertBreak(ref type); // SETLONG(Arg,nArg1); // AutoWrap(DISPATCH_METHOD, &result, WdSel, L"InsertBreak", 1, Arg); // VariantClear(&Arg); UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "InsertSymbol")) { //****************************************************************************** // InsertSymbol(CharacterNumber as Long, Font as String) int characterNumber = nArg1; object font = sArg; WdSel.InsertSymbol(characterNumber, ref font, ref missingObj, ref missingObj); #if false SETLONG(Arg,nArg1); // get char number SETSTR(Arg2,sArg); // get font AutoWrap(DISPATCH_METHOD, &result, WdSel, L"InsertSymbol", 2, Arg2, Arg); VariantClear(&Arg); VariantClear(&Arg2); #endif } //****************************************************************************** else if (Lex.Eq(command, "Cells.Merge")) { // merge cells together //****************************************************************************** WdSel.Cells.Merge(); #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Cells", 0); WdTemp = result.pdispVal; AutoWrap(DISPATCH_METHOD, &result, WdTemp, L"Merge", 0); #endif } //****************************************************************************** else if (Lex.Eq(command, "MoveLeft")) { // units, count //****************************************************************************** if (nArg2 <= 0) nArg2 = 1; object unit = nArg1; object count = nArg2; WdSel.MoveLeft(ref unit, ref count, ref missingObj); #if false SETLONG(Arg1,nArg1); SETLONG(Arg2,nArg2); AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveLeft", 2, Arg2, Arg1); VariantClear(&Arg1); VariantClear(&Arg2); #endif UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "MoveRight")) { // units, count, extend //****************************************************************************** object extend; if (nArg2 <= 0) nArg2 = 1; object unit = nArg1; object count = nArg2; if (nArg3 <= 0) extend = missingObj; else extend = nArg3; WdSel.MoveRight(ref unit, ref count, ref extend); #if false SETLONG(Arg1,nArg1); SETLONG(Arg2,nArg2); SETLONG(Arg3,nArg3); AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveRight", 3, Arg3, Arg2, Arg1); VariantClear(&Arg1); VariantClear(&Arg2); VariantClear(&Arg3); #endif UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "MoveDown")) { // units, count //****************************************************************************** if (nArg2 <= 0) nArg2 = 1; object unit = nArg1; object count = nArg2; WdSel.MoveDown(ref unit, ref count, ref missingObj); #if false SETLONG(Arg1,nArg1); SETLONG(Arg2,nArg2); AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveDown", 2, Arg2, Arg1); VariantClear(&Arg1); VariantClear(&Arg2); #endif UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "MoveUp")) { // units, count //****************************************************************************** if (nArg2 <= 0) nArg2 = 1; object unit = nArg1; object count = nArg2; WdSel.MoveUp(ref unit, ref count, ref missingObj); #if false SETLONG(Arg1,nArg1); SETLONG(Arg2,nArg2); AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveUp", 2, Arg2, Arg1); VariantClear(&Arg1); VariantClear(&Arg2); #endif UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "PageSetup.Orientation")) { //****************************************************************************** if (nArg1 == 0) WdSel.PageSetup.Orientation = WdOrientation.wdOrientPortrait; WdSel.PageSetup.Orientation = WdOrientation.wdOrientLandscape; #if false release_obj(WdTemp); AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"PageSetup", 0); WdTemp = result.pdispVal; SETLONG(Arg,nArg1); AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Orientation", 1, Arg); VariantClear(&Arg); #endif } //****************************************************************************** else if (Lex.Eq(command, "PageSetup.Margins")) { //****************************************************************************** WdSel.PageSetup.TopMargin = nArg1; WdSel.PageSetup.BottomMargin = nArg2; WdSel.PageSetup.LeftMargin = nArg3; WdSel.PageSetup.RightMargin = nArg4; } //****************************************************************************** else if (Lex.Eq(command, "PageSetup.PageSize")) { //****************************************************************************** WdSel.PageSetup.PageWidth = nArg1; WdSel.PageSetup.PageHeight = nArg2; } //****************************************************************************** else if (Lex.Eq(command, "ParagraphFormat.Alignment")) { //****************************************************************************** WdSel.ParagraphFormat.Alignment = (WdParagraphAlignment)nArg1; } //****************************************************************************** else if (Lex.Eq(command, "Cells.VerticalAlignment")) //****************************************************************************** { WdSel.Cells.VerticalAlignment = (WdCellVerticalAlignment)nArg1; } //****************************************************************************** else if (Lex.Eq(command, "Paste")) //****************************************************************************** { WdSel.Paste(); } //****************************************************************************** else if (Lex.Eq(command, "PasteSpecial")) { //****************************************************************************** // PasteSpecial(IconIndex, Link, Placement, DisplayAsIcon, DataType) object iconIndex = 0; object link = false; object placement = InLine; object displayAsIcon = false; object dataType = nArg1; // set type of data to paste // ClientLog.Message("Before PasteSpecial"); // TST & PRD WdSel.PasteSpecial(ref iconIndex, ref link, ref placement, ref displayAsIcon, ref dataType, ref missingObj, ref missingObj); // ClientLog.Message("After PasteSpecial"); } //****************************************************************************** else if (Lex.Eq(command, "InsertStructure")) //****************************************************************************** // Selection.InlineShapes.AddOLEObject ClassType:="ISISServer", FileName:= _ // "C:\Isis\sketch1-small.skc", LinkToFile:=False, DisplayAsIcon:=False // This is significantly slower than a paste { object classType = "ISISServer"; object fileName = sArg; WdSel.InlineShapes.AddOLEObject( ref classType, ref fileName, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj); } //****************************************************************************** else if (Lex.Eq(command, "Rows.AllowBreakAcrossPages")) { // keep all contents of row on same page //****************************************************************************** WdSel.Rows.AllowBreakAcrossPages = nArg1; } //****************************************************************************** else if (Lex.Eq(command, "Rows.HeadingFormat")) { // mark rows as headings //****************************************************************************** WdSel.Rows.HeadingFormat = nArg1; } //****************************************************************************** else if (Lex.Eq(command, "SaveAs")) { // save file in .doc format //****************************************************************************** try { File.Delete(sArg); } // delete any existing file catch (Exception ex) { }; object fileName = sArg; object fileFormat = WdSaveFormat.wdFormatDocument; WdDoc.SaveAs( ref fileName, // FileName ref fileFormat, // FileFormat ref missingObj, // LockComments ref missingObj, // Password ref missingObj, // AddToRecentFiles ref missingObj, // WritePassword ref missingObj, // ReadOnlyRecommended ref missingObj, // EmbedTrueTypeFonts ref missingObj, // SaveNativePictureFormat ref missingObj, // SaveFormsData ref missingObj, // SaveAsAOCELetter ref missingObj, // Encoding ref missingObj, // InsertLineBreaks ref missingObj, // AllowSubstitutions ref missingObj, // LineEnding ref missingObj); // AddBiDiMarks } //****************************************************************************** else if (Lex.Eq(command, "ScreenUpdating")) { //****************************************************************************** WdApp.ScreenUpdating = bArg; } //****************************************************************************** else if (Lex.Eq(command, "SelectColumn")) { // select current column of table //****************************************************************************** WdSel.SelectColumn(); // AutoWrap(DISPATCH_METHOD, NULL, WdSel, L"SelectColumn", 0); UpdateSelection(); } //****************************************************************************** else if (Lex.Eq(command, "SelectRow")) { // select current row of table //****************************************************************************** WdSel.SelectRow(); UpdateSelection(); } //****************************************************************************** else if (Lex.Eq(command, "Tables.Add")) { // number of rows & cols supplied //****************************************************************************** WdTables = WdDoc.Tables; Microsoft.Office.Interop.Word.Range range = WdSel.Range; int numRows = nArg1; int numCols = nArg2; WdTable = WdTables.Add(range, numRows, numCols, ref missingObj, ref missingObj); WdTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; WdTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; UpdateSelection(); } //****************************************************************************** else if (Lex.Eq(command, "TableSelect")) { //****************************************************************************** WdTable.Select(); UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "TypeParagraph")) { //****************************************************************************** WdSel.TypeParagraph(); UpdateSelection(); } //****************************************************************************** else if (Lex.Eq(command, "TypeText")) { //****************************************************************************** WdSel.TypeText(sArg); // SETSTR(Arg,sArg); // AutoWrap(DISPATCH_METHOD, &result, WdSel, L"TypeText", 1, Arg); // VariantClear(&Arg); UpdateSelection(); } //****************************************************************************** else if (Lex.Eq(command, "Visible")) { //****************************************************************************** WdApp.Visible = bArg; #if false SETBOOL(True,1); SETBOOL(False,0); if (strcmpi((CCP)sArg,"true)) AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdApp, L"Visible", 1, True); else AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdApp, L"Visible", 1, False); #endif } //****************************************************************************** else throw new Exception("WordOp - Invalid operation " + command); //****************************************************************************** return ""; // everything must be ok } // end of try
private void Print_Jornal() { // Инициализация Word this.Cursor = Cursors.WaitCursor; Word.Application o_Word = new Word.Application(); Word.Document o_Doc = new Word.Document(); string d_PrintName = o_Word.ActivePrinter; string n_PrintName = comboBox1.SelectedItem.ToString(); if (chkVisible.Checked) { o_Word.Visible = false; } else { o_Word.Visible = true; } string path_toFile = txtJornal.Text + "\\" + comboBox2.SelectedItem.ToString(); string dt_pick = dTPicker.Value.ToString("dd MMMM yyyy г."); object fileNameJorn = path_toFile; Object confirmConversions = Type.Missing; Object readOnly = Type.Missing; Object addToRecentFiles = Type.Missing; Object passwordDocument = Type.Missing; Object passwordTemplate = Type.Missing; Object revert = Type.Missing; Object writePasswordDocument = Type.Missing; Object writePasswordTemplate = Type.Missing; Object format = Type.Missing; Object encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingOEMCyrillicII; Object visible = Type.Missing; Object openConflictDocument = Type.Missing; Object openAndRepair = Type.Missing; Object documentDirection = Type.Missing; Object noEncodingDialog = Type.Missing; o_Word.Documents.Open(ref fileNameJorn, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openConflictDocument, ref openAndRepair, ref documentDirection, ref noEncodingDialog); o_Doc = o_Word.Documents.Application.ActiveDocument; Word.Selection o_Sel = o_Word.Selection; o_Sel.HomeKey(Unit: Word.WdUnits.wdStory, Extend: Word.WdMovementType.wdMove); o_Sel.EndKey(Unit: Word.WdUnits.wdLine, Extend: Type.Missing); o_Sel.TypeText(" " + dt_pick); o_Word.ActivePrinter = n_PrintName; Object background = Type.Missing; Object append = Type.Missing; Object range = Type.Missing; Object outputFileName = Type.Missing; Object from = Type.Missing; Object to = Type.Missing; Object item = Type.Missing; Object copies = Type.Missing; Object pages = Type.Missing; Object pageType = Type.Missing; Object printToFile = Type.Missing; Object collate = Type.Missing; Object fileName = Type.Missing; Object activePrinterMacGX = Type.Missing; Object manualDuplexPrint = Type.Missing; Object printZoomColumn = Type.Missing; Object printZoomRow = Type.Missing; Object printZoomPaperWidth = Type.Missing; Object printZoomPaperHeight = Type.Missing; o_Doc.PrintOut(ref background, ref append, ref range, ref outputFileName, ref from, ref to, ref item, ref copies, ref pages, ref pageType, ref printToFile, ref collate, ref activePrinterMacGX, ref manualDuplexPrint, ref printZoomColumn, ref printZoomRow, ref printZoomPaperWidth, ref printZoomPaperHeight); o_Word.ActivePrinter = d_PrintName; Thread.Sleep(2000); Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; Object originalFormat = Type.Missing; Object routeDocument = Type.Missing; ((Word._Application)o_Word).Quit(ref saveChanges, ref originalFormat, ref routeDocument); o_Word = null; this.Cursor = Cursors.Default; tSSlb.Text = "Файл " + comboBox2.SelectedItem.ToString() + " отправлен на " + n_PrintName; }
public void Format_vipLS() { // Инициализация Word this.Cursor = Cursors.WaitCursor; Word.Application o_Word = new Word.Application(); Word.Document o_Doc = new Word.Document(); string d_PrintName = o_Word.ActivePrinter; string n_PrintName = comboBox1.SelectedItem.ToString(); if (chkVisible.Checked) { o_Word.Visible = false; } else { o_Word.Visible = true; } //Открытие и редактирование документа Object filename = txtFrom.Text + "\\vips.txt"; Object confirmConversions = Type.Missing; Object readOnly = Type.Missing; Object addToRecentFiles = Type.Missing; Object passwordDocument = Type.Missing; Object passwordTemplate = Type.Missing; Object revert = Type.Missing; Object writePasswordDocument = Type.Missing; Object writePasswordTemplate = Type.Missing; Object format = Type.Missing; Object encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingOEMCyrillicII; Object visible = Type.Missing; Object openConflictDocument = Type.Missing; Object openAndRepair = Type.Missing; Object documentDirection = Type.Missing; Object noEncodingDialog = Type.Missing; if (!System.IO.File.Exists(filename.ToString())) { o_Word.Visible = true; MessageBox.Show("Файл " + filename.ToString() + " не найден.", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } o_Word.Documents.Open(ref filename, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openConflictDocument, ref openAndRepair, ref documentDirection, ref noEncodingDialog); o_Doc = o_Word.Documents.Application.ActiveDocument; //o_Doc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA3; o_Doc.PageSetup.PageWidth = o_Word.CentimetersToPoints(29.7f); o_Doc.PageSetup.PageHeight = o_Word.CentimetersToPoints(42f); o_Doc.PageSetup.LeftMargin = o_Word.CentimetersToPoints(1.27f); o_Doc.PageSetup.RightMargin = o_Word.CentimetersToPoints(1.27f); o_Doc.PageSetup.TopMargin = o_Word.CentimetersToPoints(1.27f); o_Doc.PageSetup.BottomMargin = o_Word.CentimetersToPoints(1.27f); Word.Find o_Find = o_Word.Selection.Find; Word.Selection o_Sel = o_Word.Selection; o_Sel.WholeStory(); o_Sel.Font.Size = 9; o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); Object p_findText = "Нереализованная отриц."; if (o_Find.Execute(ref p_findText, MatchCase: false, MatchWholeWord: false, MatchWildcards: false, MatchSoundsLike: Type.Missing, MatchAllWordForms: false, Forward: true, Wrap: Type.Missing, Format: false, ReplaceWith: Type.Missing, Replace: Type.Missing)) { o_Sel.EndKey(Unit: Word.WdUnits.wdLine, Extend: Type.Missing); o_Sel.HomeKey(Unit: Word.WdUnits.wdStory, Extend: Word.WdMovementType.wdExtend); o_Sel.Delete(); o_Sel.Delete(); } else { o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); Object s_findText = "Расходы по процентам"; if (o_Find.Execute(ref s_findText, MatchCase: false, MatchWholeWord: false, MatchWildcards: false, MatchSoundsLike: Type.Missing, MatchAllWordForms: false, Forward: true, Wrap: Type.Missing, Format: false, ReplaceWith: Type.Missing, Replace: Type.Missing)) { o_Sel.EndKey(Unit: Word.WdUnits.wdLine, Extend: Type.Missing); o_Sel.HomeKey(Unit: Word.WdUnits.wdStory, Extend: Word.WdMovementType.wdExtend); o_Sel.Delete(); o_Sel.Delete(); } else { MessageBox.Show("Текст поиска не найден.", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error); o_Word.Visible = true; return;; } } //int pars = o_Doc.Paragraphs.Count;// узнаем количество строк в документе int PagesCount = o_Word.Documents.Application.ActiveDocument.Content.ComputeStatistics(Word.WdStatistic.wdStatisticPages); for (int i = 1; i <= PagesCount; i++) { o_Sel.GoTo(Word.WdGoToItem.wdGoToPage, Word.WdGoToDirection.wdGoToAbsolute, PagesCount, i); o_Sel.HomeKey(Unit: Word.WdUnits.wdLine, Extend: Type.Missing); o_Sel.MoveRight(Unit: Type.Missing, Count: 68, Extend: Word.WdMovementType.wdMove); o_Sel.ColumnSelectMode = true; o_Sel.MoveRight(Unit: Type.Missing, Count: 85, Extend: Word.WdMovementType.wdMove); o_Sel.MoveDown(Unit: Word.WdUnits.wdLine, Count: 109, Extend: Word.WdMovementType.wdMove); o_Sel.ColumnSelectMode = false; //MessageBox.Show("Остановка"); o_Sel.Delete(); //o_Sel.HomeKey(Unit: Word.WdUnits.wdLine, Extend: Type.Missing); //o_Sel.MoveDown(Unit: Word.WdUnits.wdLine, Count: 109, Extend: Type.Missing); } o_Doc.PageSetup.PageWidth = o_Word.CentimetersToPoints(21f); o_Doc.PageSetup.PageHeight = o_Word.CentimetersToPoints(29.7f); //o_Doc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA4; o_Doc.PageSetup.LeftMargin = o_Word.CentimetersToPoints(2.35f); o_Word.ActivePrinter = n_PrintName; Object background = Type.Missing; Object append = Type.Missing; Object range = Type.Missing; Object outputFileName = Type.Missing; Object from = Type.Missing; Object to = Type.Missing; Object item = Type.Missing; Object copies = Type.Missing; Object pages = Type.Missing; Object pageType = Type.Missing; Object printToFile = Type.Missing; Object collate = Type.Missing; Object fileName = Type.Missing; Object activePrinterMacGX = Type.Missing; Object manualDuplexPrint = Type.Missing; Object printZoomColumn = Type.Missing; Object printZoomRow = Type.Missing; Object printZoomPaperWidth = Type.Missing; Object printZoomPaperHeight = Type.Missing; o_Doc.PrintOut(ref background, ref append, ref range, ref outputFileName, ref from, ref to, ref item, ref copies, ref pages, ref pageType, ref printToFile, ref collate, ref activePrinterMacGX, ref manualDuplexPrint, ref printZoomColumn, ref printZoomRow, ref printZoomPaperWidth, ref printZoomPaperHeight); o_Word.ActivePrinter = d_PrintName; Thread.Sleep(2000); Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; Object originalFormat = Type.Missing; Object routeDocument = Type.Missing; ((Word._Application)o_Word).Quit(ref saveChanges, ref originalFormat, ref routeDocument); o_Word = null; this.Cursor = Cursors.Default; tSSlb.Text = "Файл " + filename + " отправлен на " + n_PrintName; }
private void Format_otvet() { // Инициализация Word this.Cursor = Cursors.WaitCursor; Word.Application o_Word = new Word.Application(); Word.Document o_Doc = new Word.Document(); string d_PrintName = o_Word.ActivePrinter; string n_PrintName = comboBox1.SelectedItem.ToString(); if (chkVisible.Checked) { o_Word.Visible = false; } else { o_Word.Visible = true; } //Открытие и редактирование документа Object filename = txtFrom.Text + "\\otvet.txt"; Object confirmConversions = Type.Missing; Object readOnly = Type.Missing; Object addToRecentFiles = Type.Missing; Object passwordDocument = Type.Missing; Object passwordTemplate = Type.Missing; Object revert = Type.Missing; Object writePasswordDocument = Type.Missing; Object writePasswordTemplate = Type.Missing; Object format = Type.Missing; Object encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingOEMCyrillicII; Object visible = Type.Missing; Object openConflictDocument = Type.Missing; Object openAndRepair = Type.Missing; Object documentDirection = Type.Missing; Object noEncodingDialog = Type.Missing; if (!System.IO.File.Exists(filename.ToString())) { o_Word.Visible = true; MessageBox.Show("Файл " + filename.ToString() + " не найден.", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } o_Word.Documents.Open(ref filename, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openConflictDocument, ref openAndRepair, ref documentDirection, ref noEncodingDialog); //Word.Document Doc = new Word.Document(); o_Doc = o_Word.Documents.Application.ActiveDocument; o_Doc.PageSetup.LeftMargin = o_Word.CentimetersToPoints(1.27f); o_Doc.PageSetup.RightMargin = o_Word.CentimetersToPoints(1.27f); o_Doc.PageSetup.TopMargin = o_Word.CentimetersToPoints(1.27f); o_Doc.PageSetup.BottomMargin = o_Word.CentimetersToPoints(1.27f); Word.Find o_Find = o_Word.Selection.Find; Word.Selection o_Sel = o_Word.Selection; o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); o_Find.Text = "ФИО: Переходченко М.В."; //Object wrap = Type.Missing; ; //Object replace = Type.Missing; ; o_Find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false, MatchWildcards: false, MatchSoundsLike: Type.Missing, MatchAllWordForms: false, Forward: true, Wrap: Type.Missing, Format: false, ReplaceWith: Type.Missing, Replace: Type.Missing); o_Sel.EndKey(Unit: Word.WdUnits.wdLine, Extend: Type.Missing); o_Sel.HomeKey(Unit: Word.WdUnits.wdStory, Extend: Word.WdMovementType.wdExtend); o_Sel.Delete(); o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); o_Find.Text = "----------------------------------------------------------------------------^p----------------------------------------------------------------------------"; o_Find.Replacement.Text = "----------------------------------------------------------------------------^m----------------------------------------------------------------------------"; Object wrap = Word.WdFindWrap.wdFindContinue; Object replace = Word.WdReplace.wdReplaceAll; o_Find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false, MatchWildcards: false, MatchSoundsLike: Type.Missing, MatchAllWordForms: false, Forward: true, Wrap: wrap, Format: false, ReplaceWith: Type.Missing, Replace: replace); o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); o_Word.ActivePrinter = n_PrintName; Object background = Type.Missing; Object append = Type.Missing; Object range = Type.Missing; Object outputFileName = Type.Missing; Object from = Type.Missing; Object to = Type.Missing; Object item = Type.Missing; Object copies = Type.Missing; Object pages = Type.Missing; Object pageType = Type.Missing; Object printToFile = Type.Missing; Object collate = Type.Missing; Object fileName = Type.Missing; Object activePrinterMacGX = Type.Missing; Object manualDuplexPrint = Type.Missing; Object printZoomColumn = Type.Missing; Object printZoomRow = Type.Missing; Object printZoomPaperWidth = Type.Missing; Object printZoomPaperHeight = Type.Missing; o_Doc.PrintOut(ref background, ref append, ref range, ref outputFileName, ref from, ref to, ref item, ref copies, ref pages, ref pageType, ref printToFile, ref collate, ref activePrinterMacGX, ref manualDuplexPrint, ref printZoomColumn, ref printZoomRow, ref printZoomPaperWidth, ref printZoomPaperHeight); int PagesCount = o_Word.Documents.Application.ActiveDocument.Content.ComputeStatistics(Word.WdStatistic.wdStatisticPages); o_Word.ActivePrinter = d_PrintName; Thread.Sleep(2000); Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; Object originalFormat = Type.Missing; Object routeDocument = Type.Missing; ((Word._Application)o_Word).Quit(ref saveChanges, ref originalFormat, ref routeDocument); o_Word = null; this.Cursor = Cursors.Default; tSSlb.Text = "Файл " + filename + " отправлен на " + n_PrintName + " Всего страниц: " + PagesCount.ToString(); }
public void Format_vedLic() { // Инициализация Word this.Cursor = Cursors.WaitCursor; Word.Application o_Word = new Word.Application(); Word.Document o_Doc = new Word.Document(); if (chkVisible.Checked) { o_Word.Visible = false; } else { o_Word.Visible = true; } string dt_pick = dTPicker.Value.ToString("dd.MM.yyyy"); string dt_pick_save = dTPicker.Value.ToString("MMdd"); string[] Filelst = System.IO.Directory.GetFiles(txtFrom.Text, "day*.txt"); if (System.IO.File.Exists(Filelst.ToString())) { o_Word.Visible = true; MessageBox.Show("Файл " + Filelst.ToString() + " не найден.", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //Открытие и редактирование документа //Object o_filename = txtFrom.Text + "\\DAY"+dt_pick_save+".TXT"; Object o_filename = Filelst[0]; Object confirmConversions = Type.Missing; Object readOnly = Type.Missing; Object addToRecentFiles = Type.Missing; Object passwordDocument = Type.Missing; Object passwordTemplate = Type.Missing; Object revert = Type.Missing; Object writePasswordDocument = Type.Missing; Object writePasswordTemplate = Type.Missing; Object format = Type.Missing; Object encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingOEMCyrillicII; Object visible = Type.Missing; Object openConflictDocument = Type.Missing; Object openAndRepair = Type.Missing; Object documentDirection = Type.Missing; Object noEncodingDialog = Type.Missing; o_Word.Documents.Open(ref o_filename, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openConflictDocument, ref openAndRepair, ref documentDirection, ref noEncodingDialog); //Редактирование документа o_Doc = o_Word.Documents.Application.ActiveDocument; o_Doc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape; o_Doc.PageSetup.LeftMargin = o_Word.CentimetersToPoints(1f); o_Doc.PageSetup.RightMargin = o_Word.CentimetersToPoints(1f); o_Doc.PageSetup.TopMargin = o_Word.CentimetersToPoints(1f); o_Doc.PageSetup.BottomMargin = o_Word.CentimetersToPoints(1f); Word.Find o_Find = o_Word.Selection.Find; Word.Selection o_Sel = o_Word.Selection; o_Sel.WholeStory(); //выделяет весь текст o_Sel.Font.Size = 4; o_Sel.HomeKey(Unit: Word.WdUnits.wdStory, Extend: Word.WdMovementType.wdMove); //o_Sel.TypeText("Ведомость открытых лицевых счетов "+dt_pick+" г."+"\r\r"); o_Sel.TypeText("Ведомость открытых лицевых счетов " + dt_pick + " г."); o_Sel.TypeParagraph(); o_Sel.TypeParagraph(); o_Sel.EndKey(Unit: Word.WdUnits.wdLine, Extend: Word.WdMovementType.wdExtend); o_Sel.Delete(); //Поиск и замена o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); o_Find.Text = "^m"; o_Find.Replacement.Text = " "; Object wrap = Word.WdFindWrap.wdFindContinue; Object replace = Word.WdReplace.wdReplaceAll; o_Find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false, MatchWildcards: false, MatchSoundsLike: Type.Missing, MatchAllWordForms: false, Forward: true, Wrap: wrap, Format: false, ReplaceWith: Type.Missing, Replace: replace); o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); o_Sel.EndKey(Unit: Word.WdUnits.wdStory, Extend: Type.Missing); o_Sel.TypeParagraph(); o_Sel.TypeParagraph(); o_Sel.TypeText("Руководитель ________________ Алпеева Галина Ивановна"); o_Sel.TypeParagraph(); o_Sel.TypeParagraph(); o_Sel.TypeText("Гл.бухгалтер ________________ Зотова Елена Сергеевна"); //Сохранение в формате .doc Object s_fileName = txtFrom.Text + "\\arch\\DAY" + dt_pick_save + ".doc"; Object fileformat = Word.WdSaveFormat.wdFormatDocument; o_Doc.SaveAs(ref s_fileName, ref fileformat); //Выход из Word без сохранения Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; Object originalFormat = Type.Missing; Object routeDocument = Type.Missing; ((Word._Application)o_Word).Quit(ref saveChanges, ref originalFormat, ref routeDocument); o_Word = null; this.Cursor = Cursors.Default; tSSlb.Text = "Файл " + o_filename + " сохранен в " + s_fileName; }
void Application_WindowBeforeRightClick(Word.Selection Sel, ref bool Cancel) { clickNumber = 0; Word.Document document = this.Application.ActiveDocument; // 全文文档对象 lineQuestion = new LineQuestion(); lineQuestion.leftAnswerList = new List<LineLeftAnswer>(); lineQuestion.rightAnswerList = new List<LineRightAnswer>(); //获取标签为"autoAnswer"的菜单项 Office.CommandBarButton addBtn = (Office.CommandBarButton)Application.CommandBars["Text"].FindControl(Office.MsoControlType.msoControlButton, missing, "autoAnswer", false); addBtn.Enabled = false; //addBtn.Click -= new Office._CommandBarButtonEvents_ClickEventHandler(_RightBtn_Click); if (!string.IsNullOrWhiteSpace(Sel.Range.Text) && Sel.Range.Text.Trim().Length >= 2 && Sel.Range.Text.Trim().Length <= 5 && Sel.Range.Text.Trim().Contains("连线")) { addBtn.Enabled = true; //object charUnit = Word.WdUnits.wdCharacter; //字符移动 object lineUnit = Word.WdUnits.wdLine; //行移动 //object paragraphUnit = Word.WdUnits.wdParagraph; //段落移动 //object storyUnit = Word.WdUnits.wdStory; // 当前文档 //object count = 3; // 移动次数 object extend = Word.WdMovementType.wdExtend; //extend对光标移动区域进行扩展选择 Sel.HomeKey(lineUnit); Sel.EndKey(lineUnit, extend); //选择光标所在段落的内容 //Sel.MoveUp(paragraphUnit); //Sel.MoveDown(paragraphUnit, extend); string currentParagraphText = Sel.Range.Text; // 获取该行文本内容 lineQuestion.currentParagraph = 0; for (int i = 1; i <= document.Paragraphs.Count; i++) { if (currentParagraphText.Trim().Equals(document.Paragraphs[i].Range.Text.Trim().ToString())) { // 获取该行在文档中的段落数 lineQuestion.currentParagraph = i; } } if (lineQuestion.currentParagraph != 0) { // 获取每一道连线题的连线行总数 lineQuestion.answerCount = validParagraphs(lineQuestion.currentParagraph); } if (lineQuestion.answerCount != 0) { for (int i = 1; i <= lineQuestion.answerCount; i++) { // 获取连线行内容 string paragraphText = document.Paragraphs[lineQuestion.currentParagraph + i].Range.Text.ToString(); // 操作连线行左侧 string leftAnswerStr = paragraphText.Substring(0, paragraphText.IndexOf(" ")); LineLeftAnswer lla = new LineLeftAnswer(); lla.leftIndex = leftAnswerStr.Substring(0, leftAnswerStr.IndexOf(".")); lla.leftAnswer = leftAnswerStr.Substring(leftAnswerStr.IndexOf(".") + 1); lineQuestion.leftAnswerList.Add(lla); // 操作连线行左侧 string rightAnswerStr = paragraphText.Substring(paragraphText.LastIndexOf(" ") + 1); LineRightAnswer lra = new LineRightAnswer(); lra.rightIndex = rightAnswerStr.Substring(0, rightAnswerStr.IndexOf(".")); lra.rightAnswer = rightAnswerStr.Substring(rightAnswerStr.IndexOf(".") + 1); lineQuestion.rightAnswerList.Add(lra); } } addBtn.Click += new Office._CommandBarButtonEvents_ClickEventHandler(_RightBtn_Click); } }
void ThisDocument_BeforeDoubleClick(object sender, Microsoft.Office.Tools.Word.ClickEventArgs e) { Document vstoDoc = Globals.Factory.GetVstoObject(this.Application.ActiveDocument); lineQuestion = new LineQuestion(); lineQuestion.leftAnswerList = new List<LineLeftAnswer>(); lineQuestion.rightAnswerList = new List<LineRightAnswer>(); Word.Selection Sel = this.Application.Selection; object charUnit = Word.WdUnits.wdCharacter; //字符移动 object lineUnit = Word.WdUnits.wdLine; //行移动 object count = 5; // 移动次数 object extend = Word.WdMovementType.wdExtend; //extend对光标移动区域进行扩展选择 Sel.MoveEnd(charUnit, count); Sel.HomeKey(lineUnit, extend); if (!string.IsNullOrWhiteSpace(Sel.Range.Text) && Sel.Range.Text.Trim().ToString().Contains("连线")) { Sel.HomeKey(lineUnit); Sel.EndKey(lineUnit, extend); string currentParagraphText = Sel.Range.Text; // 获取该行文本内容 lineQuestion.currentParagraph = 0; for (int i = 1; i <= vstoDoc.Paragraphs.Count; i++) { if (currentParagraphText.Trim().Equals(vstoDoc.Paragraphs[i].Range.Text.Trim().ToString())) { // 获取该行在文档中的段落数 lineQuestion.currentParagraph = i; break; } } if (lineQuestion.currentParagraph != 0) { // 获取每一道连线题的连线行总数 lineQuestion.answerCount = validParagraphs(lineQuestion.currentParagraph); } if (lineQuestion.answerCount != 0) { for (int i = 1; i <= lineQuestion.answerCount; i++) { // 获取连线行内容 string paragraphText = vstoDoc.Paragraphs[lineQuestion.currentParagraph + i].Range.Text.ToString(); // 操作连线行左侧 string leftAnswerStr = paragraphText.Substring(0, paragraphText.IndexOf(" ")); LineLeftAnswer lla = new LineLeftAnswer(); lla.leftIndex = leftAnswerStr.Substring(0, leftAnswerStr.IndexOf(".")); lla.leftAnswer = leftAnswerStr.Substring(leftAnswerStr.IndexOf(".") + 1); lineQuestion.leftAnswerList.Add(lla); // 操作连线行左侧 string rightAnswerStr = paragraphText.Substring(paragraphText.LastIndexOf(" ") + 1); LineRightAnswer lra = new LineRightAnswer(); lra.rightIndex = rightAnswerStr.Substring(0, rightAnswerStr.IndexOf(".")); lra.rightAnswer = rightAnswerStr.Substring(rightAnswerStr.IndexOf(".") + 1); lineQuestion.rightAnswerList.Add(lra); } } if(lineQuestion != null) { LineSelectAnswerForm answerForm = new LineSelectAnswerForm(lineQuestion) { StartPosition = FormStartPosition.CenterParent }; answerForm.AnswerEvent += (str) => { answer = str; }; // 获得答案 answerForm.ShowDialog(); Word.Document document = this.Application.ActiveDocument; string originalTxt = document.Paragraphs[lineQuestion.currentParagraph].Range.Text.ToString(); originalTxt = originalTxt.Substring(0, originalTxt.IndexOf("]", 5) + 1); string currentTxt = originalTxt + answer + "\n"; answer = null; document.Paragraphs[lineQuestion.currentParagraph].Range.Text = currentTxt; // 替换原段落的内容 } } }