c# - Reading and Modifying text of Word doc using VSTO -
i writing plugin of ms word. still in stages of learning vsto. far have in word document user written text (a finish word document) in next form:
hello, name <%name%>. <%age%> years old , live in <%country%>.
those <%%> variables user drag , drop custom task pane.
what i'll doing replacing variables actual info values read info file. looking way read content of current active document in string, replace variables dummy info values , replace old document variable values new 1 actual values replaced in place of name, age etc. preferably in onsaveas event that's not available i'll have in beforesave
event.
in short looking way to:
read contents of current document. modify contents. write them back.i've been searching web , msdn hours can't find useful or maybe can't implement because i'm newbie on this.
some of articles read accomplish are:
add-in in vsto - how text word document using ribbon button
how read & write text word document using vsto in c#
globals.thisaddin.application.selection.text;
this gives selected text need text of document selected , non selected both.
current code in thisaddin.cs is:
using system; using system.collections.generic; using system.linq; using system.text; using system.xml.linq; using word = microsoft.office.interop.word; using office = microsoft.office.core; using microsoft.office.tools.word; namespace dragdrop { public partial class thisaddin { private void thisaddin_startup(object sender, system.eventargs e){globals.thisaddin.customtaskpanes.add(new orderslistusercontrol(), "drag , drop list items on word doc").visible = true;} private void thisaddin_shutdown(object sender, system.eventargs e){} public void ondropoccurred(object data) //adding dropped text on current cursor position. { word.selection currentselection = application.selection; currentselection.typetext(data.tostring()); } #region vsto generated code /// <summary> /// required method designer back upwards - not modify /// contents of method code editor. /// </summary> private void internalstartup() { this.startup += new system.eventhandler(thisaddin_startup); this.shutdown += new system.eventhandler(thisaddin_shutdown); } #endregion } }
any sort of help/directions more welcome. thanks.
edit: managed contents using:
globals.thisaddin.application.activedocument.range(0, 5).text
but issue if end range exceeds total length of document crash! how length of document in order provide sec argument, or there improve way it? wondering reading text , writing create text lose it's formatting , styling there way preserve want achieve? lot clearing out these confusions.
use content property of document first , lastly index of document's range
microsoft.office.interlop.word._document odoc=globals.thisaddin.application.activedocument; object start=odoc.content.start; object end=odoc.content.end; //select entire document odoc.range(ref start,ref end).select();
c# .net ms-word vsto
No comments:
Post a Comment