本文整理汇总了C#中Microsoft.Office.Interop.Word.Document.Range方法的典型用法代码示例。如果您正苦于以下问题:C# Document.Range方法的具体用法?C# Document.Range怎么用?C# Document.Range使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Office.Interop.Word.Document
的用法示例。
在下文中一共展示了Document.Range方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AddToc
public void AddToc()
{
wordApp = new Application();
object file = filePath;
try
{
wordDocument = wordApp.Documents.Open(ref file, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing
);
Range tocRange = wordDocument.Range(0, 0);
TableOfContents toc = wordDocument.TablesOfContents.Add(tocRange, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing);
toc.Update();
int end = toc.Range.End;
Range tocEnd = wordDocument.Range(end, end);
tocEnd.InsertParagraphBefore();
tocEnd.InsertBreak(WdBreakType.wdPageBreak);
}
catch (COMException ex)
{
throw new InvalidOperationException("Invalid Document", ex);
}
finally {
Dispose();
}
}
示例2: SaveFileAs
public override void SaveFileAs(string fileName, FileType type)
{
object Visible = false;
object start1 = 0;
object end1 = 0;
WordApp = new Word.Application();
doc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
Range rng = doc.Range(ref start1, ref missing);
rng.InsertAfter(parsedFile.contentRaw);
object filename = fileName;
doc.SaveAs(ref filename, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
WordApp.Visible = true;
//doc.RemoveDocumentInformation(WdRemoveDocInfoType.wdRDIAll);
//doc.DocumentInspectors;
}
示例3: CopyBodyToMeeting
private void CopyBodyToMeeting(AppointmentItem ai, ref MeetingItem meetingItem)
{
ThisAddIn.g_log.Info("Copy AppointmentItem body to MeetingItem enter");
Word.Document Doc = new Word.Document();
Word.Document Doc2 = new Word.Document();
Word.Application App1;
Word.Selection Sel;
Doc = ai.GetInspector.WordEditor as Word.Document;
if (Doc != null)
{
ThisAddIn.g_log.Info(string.Format("appointmentItem doc length is {0}.", Doc.Content.Text.Length));
Doc.Activate();
Doc.Select();
App1 = Doc.Windows.Application;
Sel = App1.Selection;
Sel.WholeStory();
Sel.Copy();
Doc2 = meetingItem.GetInspector.WordEditor as Word.Document;
if (Doc2 != null)
{
Doc2.Activate();
object start = 0;
Range newRang = Doc2.Range(ref start, ref start);
int ioo = Doc2.Sections.Count;
Section sec = Doc2.Sections[1];
sec.Range.InsertBreak(Type.Missing);//插入换行符
sec.Range.PasteAndFormat(WdRecoveryType.wdPasteDefault);
meetingItem.Save();
ThisAddIn.g_log.Info(string.Format("meetingItem doc length is {0}.", Doc2.Content.Text.Length));
//ThisAddIn.g_log.Info(string.Format("mailItem body length is {0}.", meetingItem.Body.Length));
if (meetingItem.Body == null || meetingItem.Body.Length < 100)
{
Doc2.Activate();
((_Inspector)(meetingItem.GetInspector)).Activate();
}
}
}
Doc = null;
Doc2 = null;
App1 = null;
Sel = null;
ThisAddIn.g_log.Info("Copy AppointmentItem body to MeetingItem exit");
}
示例4: Main
static void Main(string[] args)
{
string finalHTML;
List<string> listString = new List<string>();
object True = true;
Word.Application app = new Word.Application();
Word.Document doc = new Word.Document();
string fileName = @"D:\Programming\C#\Word To Markup Converter\hello world.docx";
doc = app.Documents.Open(fileName, Type.Missing, True);
//foreach (Word.Paragraph para in doc.Paragraphs)
//{
// para.Range.Copy();
// stripClasses(Clipboard.GetText(TextDataFormat.Html));
//}
Word.ListParagraphs listpara = doc.ListParagraphs;
IEnumerator ienum = doc.ListParagraphs.GetEnumerator();
List<Tuple<string, Word.WdListType, int>> items = new List<Tuple<string, Word.WdListType, int>>();
while (ienum.MoveNext())
{
Word.Range r = ((Word.Paragraph)ienum.Current).Range;
items.Add(new Tuple<string, Word.WdListType, int>(r.Text, r.ListFormat.ListType, r.ListFormat.ListLevelNumber));
}
items.Reverse();
if (items.Count > 0)
{
listString = createList(items);
}
doc.SelectAllEditableRanges();
doc.Range().Copy();
string returnHTMLText = null;
if (Clipboard.ContainsText(TextDataFormat.Html))
{
Console.WriteLine("html");
returnHTMLText = Clipboard.GetText(TextDataFormat.Html);
//Console.WriteLine(returnHTMLText);
stripClasses(returnHTMLText, listString);
}
else
{
Console.WriteLine("no html");
//Console.WriteLine(doc.);
//returnHTMLText = Clipboard.GetText(TextDataFormat.Html);
}
doc.Close();
app.Quit();
Console.WriteLine("closed");
while (true) ;
}
示例5: HookCallback
// Callback function for Keyboard hook.
private static IntPtr HookCallback(
int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
IntPtr active = GetForegroundWindow();
if (!(active.Equals(self.MainWindowHandle) || active.Equals(GUIManager.GUIHandle)))
{
inputStatus = KEYBOARD_IDLE;
GUIManager.disappear();
}
#region KeyCheck
else
{
currDoc = ThisAddIn.getCurrDocument();
int vkCode = Marshal.ReadInt32(lParam);
if (active.Equals(GUIManager.GUIHandle))
{
hotkeyTimer.Start();
int maxCount = tempList.Count - wrappedPage * REFERENCE_PER_PAGE - 1;
if (vkCode == KeyboardMapping.Keys["1"])
{
selectedItem = Math.Min(0, maxCount);
}
else if (vkCode == KeyboardMapping.Keys["2"])
{
selectedItem = Math.Min(1, maxCount);
}
else if (vkCode == KeyboardMapping.Keys["3"])
{
selectedItem = Math.Min(2, maxCount);
}
else if (vkCode == KeyboardMapping.Keys["4"])
{
selectedItem = Math.Min(3, maxCount);
}
else if (vkCode == KeyboardMapping.Keys["5"])
{
selectedItem = Math.Min(4, maxCount);
}
else if (vkCode == KeyboardMapping.Keys["VK_LEFT"])
{
if (wrappedPage > 0) wrappedPage -= 1;
selectedItem = 0;
}
else if (vkCode == KeyboardMapping.Keys["VK_RIGHT"])
{
if (wrappedPage < maxPage)
{
wrappedPage += 1;
selectedItem = 0;
}
else selectedItem = maxCount;
}
GUIManager.chooseItem(selectedItem, wrappedPage);
}
if (inputStatus == KEYBOARD_IDLE)
{
// Register place for starting typing.
inputStatus = KEYBOARD_TYPING;
Messenger.message("User is Typing!");
selStart = currDoc.Application.Selection.End;
//start Timer
resetTimer();
}
else if (inputStatus == KEYBOARD_TYPING)
{
resetTimer();
}
else if (inputStatus == KEYBOARD_PREFLISTSHOWED)
{
if (checkHotKey(vkCode, extendSentenceHotKey, 1))
{
string extending = tempList[wrappedPage * REFERENCE_PER_PAGE + selectedItem].getContent();
sentenceLength.Add(extending.Length);
int tempPos = selEnd;
// Print string
currDoc.Application.Selection.Start = selEnd;
currDoc.Application.Selection.End = selEnd;
currDoc.Application.Selection.TypeText(extending);
// Move cursor
selEnd = tempPos + extending.Length;
selStart = tempPos;
rng = currDoc.Range(selStart, selEnd);
rng.Select();
Messenger.message("Sentence Extended!");
}
else if (checkHotKey(vkCode, deleteSentenceHotKey, 4))
//.........这里部分代码省略.........
示例6: startMarkup
///<summary>
///Procedimiento al que llamaremos para inciar el proceso de marcación
///</summary>
public void startMarkup()
{
if (log.IsInfoEnabled) log.Info("Begin");
/* Declaracion de variables */
Boolean marked = false;
Boolean parsed = false;
String originalString = null;
String fixedMarkedString = null;
String issn = null;
String pathXML = null;
String clearTag = null;
Word.Selection docSeleccion = null;
this.xmlDoc = new XmlDocument();
List<MarkupStruct> citas = null;
RegexOptions options = RegexOptions.None;
Regex objRegExp = new Regex(@"\[[^\]]+?\]", options);;
Dictionary<String, String> altRule = new Dictionary<String, String>(){
{"doc", "0000-0000"},
{"article", "XXXX-XXXX"},
{"text", "XXXX-XXXX"}
};
/*Definiendo directorios de los xml*/
if (ApplicationDeployment.IsNetworkDeployed)
{
pathXML = Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, "regex.xml");
}
else {
pathXML = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "regex.xml");
}
/*Verificamos si vamos a usar un archivo externo para las reglas*/
if (Settings.Default.useExternalRegexFile) {
pathXML = Settings.Default.externalRegexFile;
}
/* Inicializamos variables */
ActiveDocument = Globals.ThisAddIn.Application.ActiveDocument;
/* Leemos y verificamos que el issn exista */
this.dtdType = "article";
issn = utils.getAttrValueInTag("article", "issn");
/* Verificamos la existencia de text */
if (issn == null) {
issn = utils.getAttrValueInTag("text", "issn");
this.dtdType = "text";
}
/* Verificamos la existencia de doc */
if (issn == null)
{
issn = utils.getAttrValueInTag("doc", "issn");
this.dtdType = "doc";
}
if (log.IsDebugEnabled) log.Debug("issn: " + issn);
if (issn == null) {
MessageBox.Show(Resources.RegexMarkup_issnNotDefined, Resources.RegexMarkup_title);
} else {
/*Asignamos el numero de version de la DTD*/
this.dtdVersion = utils.getAttrValueInTag(this.dtdType, "version");
this.dtdVersion = this.dtdVersion == null ? "4.0" : this.dtdVersion;
/* Cargamos el archivo xml donde se encuetran los patrones de las revistas */
try
{
this.xmlDoc.Load(pathXML);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return;
}
/* Leemos el nodo correspondiente al issn de la revista */
this.serialNode = this.xmlDoc.SelectSingleNode("//*[@issn=\"" + issn + "\"]");
/* Si no existe una regla para la revista cargamos una generica */
this.serialNode = this.serialNode == null ? this.xmlDoc.SelectSingleNode("//*[@issn=\"" + altRule[this.dtdType] + "\"]") : this.serialNode;
/* Asignamos el estilo de la citación */
this.citationStyle = this.serialNode.SelectSingleNode("norm").InnerText.Trim();
if (this.dtdType == "doc")
this.citationStyle = "refs";
/* Verificamos que la seleccion sea del parrafo completo */
Word.Range start = Globals.ThisAddIn.Application.Selection.Range;
docSeleccion = Globals.ThisAddIn.Application.Selection;
if (docSeleccion.Start != docSeleccion.Paragraphs.First.Range.Start || docSeleccion.End != docSeleccion.Paragraphs.Last.Range.End){
MessageBox.Show(Resources.RegexMarkup_selectCitationComplete, Resources.RegexMarkup_title);
} else {
/* Asignamos el texto de la seleccion a subjectString */
if (log.IsInfoEnabled) log.Info("Select paragraphs");
/* Inicializando arratlist de citas */
citas = new List<MarkupStruct>();
/*Creamos una instancia del formulario*/
this.formValidate = ValidateMarkup.Instance;
this.formValidate.CitationStyle = this.citationStyle;
this.formValidate.DtdVersion = this.dtdVersion;
this.formValidate.DtdType = this.dtdType;
this.formValidate.updateDTDInfo();
/* Buscando parrafo por parrafo */
foreach (Word.Paragraph parrafo in docSeleccion.Paragraphs){
fixedMarkedString = null;
marked = false;
parsed = false;
//.........这里部分代码省略.........
示例7: buttonPDF_Click
private void buttonPDF_Click(object sender, RoutedEventArgs e)
{
var wrd_name = Convert.ToString(comboBox.SelectedValue);
var xls_name = textBoxExcelPath.Text;
if (string.IsNullOrEmpty(wrd_name))
{
MessageBox.Show("Выберите шаблон КП");
return;
}
ProgressWnd pw = new ProgressWnd("Создаем КП по шаблону...");
pw.Show();
string fn = "";
try
{
WordApp = new Wd.Application() { Visible = false };
WordDoc = WordApp.Documents.Open(wrd_name);
fn=SaveW(WordApp, WordDoc);
var ad = DataContext as AllData;
ReplaceAll(WordDoc,"[OurCompany]", ad.Our.OurCompany);
ReplaceAll(WordDoc, "[ForWho]", ad.ForWho);
ReplaceAll(WordDoc, "[ContractPeriodYears]", ad.HowLongYears);
ReplaceAll(WordDoc, "[ServiceType]", ad.ServiceType);
ReplaceAll(WordDoc, "[DaysToStart]", ad.DaysToStart);
ReplaceAll(WordDoc, "[DateStart]", ad.DateStart);
ReplaceAll(WordDoc, "[CostMonthString]", ad.CostMonthString);
ReplaceAll(WordDoc, "[CostMonth]", ad.CostMonth);
ReplaceAll(WordDoc, "[CostYear]", (o2d(ad.CostMonth) * 12).ToString());
ReplaceAll(WordDoc, "[Address]", ad.Address);
ReplaceAll(WordDoc, "[Date]", ad.Date);
ReplaceAll(WordDoc, "[Area]", ad.Area.ToString());
ReplaceAll(WordDoc, "[NameObject]", ad.ForWho);
int kk = 1;
foreach(var ee in ad.e1)
{
var trg="[Extra" + kk + "]";
if (ee.IsSelected==true)
{
ReplaceAll(WordDoc, trg, ee.Text);
}
else
{
WordDoc.Bookmarks["bExtra" + kk].Range.Delete();
ReplaceAll(WordDoc, trg, "");
}
++kk;
}
kk = 1;
foreach (var ee in ad.e2)
{
var trg = "[Sod" + kk + "]";
if (ee.IsSelected == true)
{
ReplaceAll(WordDoc, trg, ee.Text);
}
else
{
WordDoc.Bookmarks["bSod" + kk].Range.Delete();
ReplaceAll(WordDoc, trg, "");
}
++kk;
}
if(radioButton.IsChecked==true)
{
ReplaceAll(WordDoc, "[NaOsnovanii]", ad.NaOsn1);
}
else
{
ReplaceAll(WordDoc, "[NaOsnovanii]", ad.NaOsn2);
}
if(checkBoxServicePlan.IsChecked==false)
{
Wd.Range delRange = WordDoc.Range();
delRange.Start=WordDoc.Bookmarks["b0"].Range.Start;
delRange.End = WordDoc.Bookmarks["b1"].Range.End;
delRange.Delete();
}
ReplaceAll(WordDoc, "[ServicePlanStart]", "");
ReplaceAll(WordDoc, "[ServicePlanEnd]", "");
//ReplaceAll(WordDoc, "[NameCost]", ad.ForWho);
//Sebestoimost
Wd.Table tt=FindTable(WordDoc, WordDoc.Bookmarks["tab6"]);
double total = 0;
foreach (var s in ad.Sebestimost)
{
tt.Rows.Add();
tt.Cell(tt.Rows.Count, 1).Range.Text = s.Name;
//.........这里部分代码省略.........
示例8: Button1_Click
protected void Button1_Click(object sender, EventArgs e)
{
object Nothing = System.Reflection.Missing.Value;//定义一个missing
wordApp = new Msword.ApplicationClass();//对wordapp进行初始化
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);//对一个wordDoc进行初始化
object filename = "F:\\aa.doc";
if (File.Exists(filename.ToString()))//判断文件是否存在
{
File.Delete(filename.ToString());//若文件存在就删除这个文件
}
wordApp.Visible = false;//设置动态建立的word文档可见
wordApp.Selection.PageSetup.LeftMargin = wordApp.CentimetersToPoints(float.Parse("2"));//设置word文档的左边距
wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse("2"));//设置word文档右边距
wordApp.ActiveWindow.HorizontalPercentScrolled = 11;//设置文档的水平滑动距离
wordApp.ActiveWindow.View.Type = Msword.WdViewType.wdOutlineView;//设置文档的页眉类型
wordApp.ActiveWindow.View.SeekView = Msword.WdSeekView.wdSeekCurrentPageHeader;//设置文档的页眉是显示在文档的头部
wordApp.ActiveWindow.ActivePane.Selection.InsertAfter("这是我的页眉内容");
wordApp.Selection.ParagraphFormat.Alignment = Msword.WdParagraphAlignment.wdAlignParagraphRight;//设置页眉内容的对齐方式
//wordApp.ActiveWindow.View.SeekView = Msword.WdSeekView.wdSeekMainDocument;//跳出页眉设置
wordApp.Selection.ParagraphFormat.LineSpacing = 11f;//设置段落的距离为11f
Msword.Paragraph para1;//定义一个段落为para1
para1 = wordDoc.Paragraphs.Add(ref Nothing);//对para1进行初始化
para1.Range.Text = "这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2";//对段落para1进行添加内容
para1.Format.CharacterUnitFirstLineIndent = 2;//设置首行缩进
para1.Range.Font.Color = Msword.WdColor.wdColorBlue;//设置字体的颜色
para1.Format.SpaceAfter = 6;//在段落para1后面设置空行为6
para1.Range.InsertParagraphAfter();//将段落para1添加到文档中
Msword.Paragraph para2;//同上
object endofdoc = "\\endofdoc";//定义标签endofdoc,"endofdoc"表示文档的末尾书签
object range1 = wordDoc.Bookmarks.get_Item(ref endofdoc).Range;//定位到文档的书签处
para2 = wordDoc.Paragraphs.Add(ref range1);//同上
para2.Range.Text = "asfdasdfasdfasdffasdfsadfasdfasfdasdfas";//同上
para2.Range.InsertParagraphAfter();//同上
Msword.Paragraph para3;//同上
object range2 = wordDoc.Bookmarks.get_Item(ref endofdoc).Range;//同上
para3 = wordDoc.Paragraphs.Add(ref range2);//同上
para3.Range.Text = "eeeeeeeeeeeeeeeeeeeeeeee";//同上
object sttar = (object)(para3.Range.Start + 2);//"para3.Range.Start "表示para3段落的开始处加上两个字符
object eend = (object)(para3.Range.Start + 2);//同上
wordDoc.Range(ref sttar, ref eend).InsertBefore("ttt");//定位到para3段落的开始处加上两个字符并添加内容"ttt"
para3.Format.CharacterUnitFirstLineIndent = 2;//设置首行缩进
para3.Range.Font.Bold = 5;//设置段落para3字体颜色
para3.Range.InsertParagraphAfter();//同上
Msword.Table table1 = wordDoc.Tables.Add(para3.Range, 8, 8, ref Nothing, ref Nothing);//在文档中添加8行8列的表格
table1.Cell(1, 1).Range.Font.Color = Msword.WdColor.wdColorBrown;//设置表格中的第1行1列的字体颜色为wdColorBrown
table1.Cell(1, 1).Range.Text = "搜点的撒旦";//在表格中的第一行第一类中添加内容
table1.Range.ParagraphFormat.Alignment = Msword.WdParagraphAlignment.wdAlignParagraphRight;//设置表格中的内容alignment
table1.Cell(3, 3).Merge(table1.Cell(8, 3));//将3行3列一直到8行3列进行组合成一列
object row = 4;
object col = 4;
table1.Cell(3, 1).Split(ref row, ref col);//将3行1列分开为4行4列
string picturefile = "D:\\ly\\应用\\test.jpg";//设置图片的路径
object linktofile = false;
object linktodoctument = true;
object x1 = (object)(para2.Range.Start);
object x2 = (object)(para2.Range.End);
object rr1 = wordDoc.Range(ref x1, ref x2);
wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(picturefile, ref linktofile, ref linktodoctument, ref rr1);//将图片添加到文档中
//将图片的外形设置为可变
Msword.Shape shape1 = wordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
shape1.WrapFormat.Type = Msword.WdWrapType.wdWrapSquare;
//保存wordDoc
wordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing);
//释放内存
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
}