Italic inline word with Interop.Word - c#

I've starting learning C#, mostly for the purpose of MS Word automation. Using Interop.Word, how can I add a line with words "one two three" with two being italic? The closest I can get is something like this:
//text with some italic words.
para.Range.Text = "one ";
Console.WriteLine(para.Range.Start);
Console.WriteLine(para.Range.End);
// <some magic methods that end the last range and start a new one in place>
para.Range.Text = "two";
para.Range.Font.Italic = 1;
Console.WriteLine(para.Range.Start);
Console.WriteLine(para.Range.End);
// <some magic methods that end the last range and start a new one in place>
para.Range.Text = " three";
Console.WriteLine(para.Range.Start);
Console.WriteLine(para.Range.End);
para.Range.InsertParagraphAfter();
As for the method I need, I tried many things, but none of them worked. The MSDN documentation is very hard to read and omit many important details.
EDIT: I finally made it worked, by creating a new range object for every word. This is about as ugly as I could imagine but as least it works:
Word.Range rng = word_doc.Range(para.Range.End - 1, para.Range.End);
rng.Text = "one ";
Console.WriteLine(rng.Start);
Console.WriteLine(rng.End);
rng = word_doc.Range(rng.End - 1, rng.End);
rng.Text = "two";
rng.Font.Italic = 1;
Console.WriteLine(rng.Start);
Console.WriteLine(rng.End);
rng = word_doc.Range(rng.End - 1, rng.End);
rng.Text = " three";
rng.Font.Italic = 0;
Console.WriteLine(rng.Start);
Console.WriteLine(rng.End);
para.Range.InsertParagraphAfter();

This is the closest I could get, the main issue with this code I made for you is that it doesn't add the text back inline, but instead adds a new line for each word it finds. Hopefully this code gives you some ideas on how to best programmatically create word documents!
Document extendedDocument = Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveDocument);
Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
Word.Paragraph para;
para = extendedDocument.Content.Paragraphs.Add(ref oMissing);
para.Range.SetRange(currentSelection.Range.Start, currentSelection.Range.End);
string string1 = "one two three";
string split1 = " ";
string match1 = "two";
string[] elements = Regex.Split(string1, split1);
foreach (var m in elements)
{
if (m.Equals(match1))
{
para.Range.Text = m + " ";
para.Range.Font.Italic = 1;
}
else
{
para.Range.Text = m + " ";
para.Range.Font.Italic = 0;
}
para.Range.InsertParagraphAfter();
}
Edit: Have a good weekend! I will try to check my SO inbox over the weekend, but I may not reply to any questions till Monday.

Related

C# compare input with keywords

ive got the following c# code:
string textBoxInput = richTextBox1.Text;
StreamReader SentencesFile = new StreamReader(#"C:\Users\Jeroen\Desktop\School\C#\opwegmetcsharp\answersSen.txt");
string Sentence = SentencesFile.ReadLine();
List<List<string>> keywordsList = new List<List<string>>();
List<string> outputSentence = new List<string>();
while (Sentence != null)
{
string keywords = Sentence.Substring(0, Sentence.IndexOf(' '));
string sentenceString = Sentence.Substring(0, Sentence.IndexOf(' ') +1);
List<string> splitKeyword = keywords.Split(',').ToList();
keywordsList.Add(splitKeyword);
outputSentence.Add(sentenceString);
}
int similar = 0;
int totalSimilar = 0;
List<string> SplitUserInput = textBoxInput.Split(' ').ToList();
And a .txt file which contains the following:
car,bmw Do you own a BMW?
car,Tesla Do you own a Tesla?
new,house Did you buy a new house?
snow,outside Is it snowing outside?
internet,down Is your internet down?
I can't figure out how i can compare every word that a user typed in the input (richTextBox1.Text) with the keywords in the .txt file ( like car and bmw for the first sentence )
And it also has to remember the sentence that has the highest amount of "hits".
I'm really stuck and searched a lot, but somehow i can't find out how i can do this.
A lot of thanks in advance!
You can use the LINQ Contains to check if a word is found in a list. But beware because it is case sensitive as password does. Use it like this:
//assuming you already list the keyword here
List<string> keywords = new List<string>() { "keyword1", "keyword2" };
Then for each sentence, supposing in this form:
string sentence1 = "Hi, this keYWord1 present! But quite malformed";
string sentence2 = "keywoRD2 and keyWOrd1 also present here, malformed";
Note: the above sentences could be your text from RichTextBox or file, it doesn't matter. Here I only show the concept.
You can do:
string[] words = sentence1.ToLower().Split(new char[] { ' ', ',', '.' });
int counter = 0;
for (int i = 0; i < words.Length; ++i){
counter += keywords.Contains(words[i]) ? 1 : 0;
}
And you can do likewise for sentence2. Whoever gets the highest counter has the highest hits.
This might be too advanced for a 1st year student but this piece of code will work for your need. Using Regex class to do matching for you. Performance-wise it's faster (AFAIK). I used a console application to work on this as I don't think it will be hard for you to use it in a WinForms/WPF application.
string textBoxInput = "car test do bmw"; // Just a sample as I am using a console app
string[] sentences = File.ReadAllLines("sentences.txt"); // Read all lines of a text file and assign it to a string array
string[] keywords = textBoxInput.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // Split textBoxInput by space
int[] matchArray = new int[sentences.Length];
for(int i = 0; i < sentences.Length; i++)
{
Regex regex = new Regex(#"\b(" + string.Join("|", keywords.Select(Regex.Escape).ToArray()) + #"+\b)", RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(sentences[i]);
matchArray[i] = matches.Count;
}
int highesMatchIndex = Array.IndexOf(matchArray, matchArray.OrderByDescending(item => item).First());
Console.WriteLine("User input: " + textBoxInput);
Console.WriteLine("Matching sentence: " + sentences[highesMatchIndex]);
Console.WriteLine("Match count: " + matchArray[highesMatchIndex]);
Console.ReadLine();

how to extrct particular string from string and increment that in c# using regex

i have created one id - i want to increment that id . for that i need to replace the string in a string
input string - KST-HYD/15-116/001/CST
i extracted 001, but im unable to replace 001 with 002
code behind
Regex regex = new Regex(#"\/(\d+)\/");
Match match = regex.Match(txtId.Text.Trim());
if (match.Success)
{
//Console.WriteLine(match.Value);
int oldid = Convert.ToInt32(match.Groups[1].Value);
int newid = oldid + 1;
string newidstring = newid.ToString();
string idformat = "KST-HYD/15-116/#/CST";
StringBuilder builder = new StringBuilder(idformat);
builder.Replace("#",newidstring);
string newGeneratedId = builder.ToString();
Response.Write(newGeneratedId);
}
here is a one liner solution
string txtId = "KST-HYD/15-116/001/CST";
string result = Regex.Replace(txtId, #"(?<=\/)\d{3}(?=\/)", s => (int.Parse(s.Value)+1).ToString("d3"));
UPDATE: RegEx:
(?<=\/) number starts with / but it's not a part of the number
\d{3} the number has always a fix length of 3
(?=\/) number ends with / but it's not a part of the number
Use string.Remove, string.Insert, and Convert.ToInt32:
string txt = match.Groups[1].Value;
int pos = match.Index; //please add this for getting the position for the match
txtId.Text = txtId.Text.Remove(pos + 1, txt.Length).Insert(pos + 1, (Convert.ToInt32(txt) + 1).ToString("d3"));
Edit: Thanks for correction from Mr. Giorgi and others. I updated the answer to position-based.
Here is how I would do this to replace exactly at the position where match is found:
var t = "KST-HYD/15-116/001/CST";
Regex regex = new Regex(#"\/(?<m>\d+)\/");
Match match = regex.Match(t);
if (match.Success)
{
string txt = match.Groups["m"].Value;
var pos = match.Index;
var vali = int.Parse(txt);
var sb = new StringBuilder(t);
sb.Remove(pos + 1, txt.Length);
sb.Insert(pos + 1, (++vali).ToString("000"));
t = sb.ToString();
}

Need to count incidents found multiple times within a text file

I'm really trying to count the number of times a regex is found within a text but there are many regex to be found within a text file.
the problem is that my code only counts the first time, the subsequent IF that contains the other regexes will not count, Everything works but the counting of on each line that error occurred :(
could you please shed some light?
int counter = 1;
string liner;
string pattern = #"access-group\s+\w+\s+out\s+interface\s+\w+";
Boolean foundMatch;
int totalOUTgroups = Lines(ofd.FileName)
.Select(line => Regex.Matches(line, pattern).Count)
.Sum();
if (totalOUTgroups > 0)
{
richTextBox2.SelectionFont = new Font("Courier New", 8);
richTextBox2.AppendText(">>> ACls installed by using access-group using the keyword OUT are NOT supported: " + "\u2028");
richTextBox2.AppendText(">>> Total of incidences found: " + totalOUTgroups.ToString() + "\u2028");
System.IO.StreamReader file = new System.IO.StreamReader(ofd.FileName);
while ((liner = file.ReadLine()) != null)
{
foundMatch = performMatch(pattern, liner);
if (foundMatch)
{
richTextBox2.AppendText("Line: " + counter + " " + liner + "\r\n");
}
counter++;
}
}
//Will end 1
// 2 Mark echo-reply ICMP
int counter2 = 1;
string liner2;
string pattern2 = #"/^(?=.*\baccess-list\b)(?=.*\beq echo-reply\b).*$/gm";
Boolean foundMatch2;
int totalIntACLInt = Lines(ofd.FileName)
.Select(line => Regex.Matches(line, pattern2).Count)
.Sum();
if (totalIntACLInt > 0)
{
richTextBox2.SelectionFont = new Font("Courier New", 8);
richTextBox2.AppendText(" " + "\u2028");
richTextBox2.AppendText(">>> Echo-reply is not necessary: " + "\u2028");
richTextBox2.AppendText(">>> Total of incidences found: " + totalIntACLInt.ToString() + "\u2028");
System.IO.StreamReader file = new System.IO.StreamReader(ofd.FileName);
while ((liner2 = file.ReadLine()) != null)
{
foundMatch2 = performMatch(pattern2, liner2);
if (foundMatch2)
{
richTextBox2.AppendText("Line:" + counter2 + " " + liner2 + "\r\n");
}
counter2++;
}
}
If I understand your question, then the problem you're having is most likely tied to your implementation of performMatch(). Post the code for performMatch() if you want help debugging that.
As #Justin lurman pointed out, try printing out each line and line number while only iterating through the file once. If Regex.Matches(line, pattern) is already working for you, then just make use of that.
For example:
int counter = 1;
string pattern = #"access-group\s+\w+\s+out\s+interface\s+\w+";
var totalMatches = 0;
var output = new StringBuilder();
foreach(var line in Lines(ofd.FileName))
{
var matches = Regex.Matches(line, pattern).Count;
if (matches > 0)
{
totalMatches += matches;
output.AppendLine(string.Format("Line: {0} {1}", counter, line));
}
counter++;
}
if(toatlMatches > 0)
{
richTextBox2.SelectionFont = new Font("Courier New", 8);
richTextBox2.AppendText(">>> ACls installed by using access-group using the keyword OUT are NOT supported: " + "\u2028");
richTextBox2.AppendText(">>> Total of incidences found: " + totalMatches.ToString() + "\u2028");
richTextBox2.AppendText(output.ToString());
}
As a warning I haven't compiled or tested the code above, so use it as a guideline. You can certainly improve upon the code further. To start you could refactor your repeated code into methods.
Update
OK, I still don't know that I'm clear on what exactly your problem is, but I wrote out some code that should achieve what it is that I think you're trying to accomplish. While writing my code I noticed some things about the code you posted that may be causing issues for you.
Your second regex /^(?=.*\baccess-list\b)(?=.*\beq echo-reply\b).*$/gm doesn't look like a valid .NET regex, it looks like a JavaScript regex literal
You're appending text to a RichTextBox control, which has a max length property you may be exceeding. I doubt you're writing out that much text, but it's possible.
When this property is set to 0, the maximum length of the text that can be entered in the control is 64 KB of characters
- source
Here is the relevant snippet from the console app I wrote that reads a text file, line by line, and applies a collection of regexes to each line. If a match is found it stores the pertinent information about each match and then prints out its finding once all lines have been examined.
class CommonError
{
public Regex Pattern { get; private set; }
public string Message { get; private set; }
public List<KeyValuePair<int, IEnumerable<string>>> Details { get; private set; }
public CommonError(Regex pattern, string message)
{
Pattern = pattern;
Message = message;
Details = new List<KeyValuePair<int, IEnumerable<string>>>();
}
}
class Program
{
static void Main(string[] args)
{
//take a file read it once and while reading each line check if that line matches any of a slew of regexes.
//if it does match a regex then add the line number and the matching text into a collection of matches for that regex.
//at the end output all the matches by regex and the totals for each pattern. Along with printing each match also print the line it was found on.
var errorsToFind = new List<CommonError>()
{
new CommonError(new Regex(#"access-group\s+\w+\s+out\s+interface\s+\w+"), "ACls installed by using access-group using the keyword OUT are NOT supported"),
new CommonError(new Regex(#"^(?=.*\baccess-list\b)(?=.*\beq echo-reply\b).*$"), "Echo-reply is not necessary")
};
var errorsFound = FindCommonErrorsInFile(".\\test-file.txt", errorsToFind);
foreach (var error in errorsFound)
{
Console.WriteLine(error.Message);
Console.WriteLine("total incidences found: " + error.Details.Count);
error.Details.ForEach(d => Console.WriteLine(string.Format("Line {0} {1}", d.Key, string.Join(",", d.Value))));
}
}
static IEnumerable<CommonError> FindCommonErrorsInFile(string pathToFile, IEnumerable<CommonError> errorsToFind)
{
var lineNumber = 1;
foreach (var line in File.ReadLines(pathToFile))
{
foreach (var error in errorsToFind)
{
var matches = error.Pattern.Matches(line);
if(matches.Count == 0) continue;
var rawMatches = matches.Cast<Match>().Select(m => m.Value);
error.Details.Add(new KeyValuePair<int, IEnumerable<string>>(lineNumber, rawMatches));
}
lineNumber++;
}
return errorsToFind.Where(e => e.Details.Count > 0);
}
}
If you're still having issues give this code a try--this time I actually compiled it and tested it. Hope this helps.

Comparing two RichTextBoxes?

I'm comparing richTextBox1 and richTextBox2 word by word.
// collect words from ritchtextbox1
String[] test = richtextbox1.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
// find each word test to richtextbox2
// if it is found then change back color of particular word to green of the
// else change back color of particular word to red in richtextbox1
test = richtextbox2.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
// find each word in test to richtextbox1
// if it is found then change back color of particular word to green of the
// else change back color of particular word to red in richtextbox2
can any one help me in code i'm little bit poor in syntax.
im taking reference of mateusz code
String[] test = richtextbox1.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
String[] test2 = richtextbox2.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
bool wordNotFound=false;
for (int i=0;i<test.lenght;i++)
for (int j=0;j<test2.length;j++){
if (test[i].equals(test2[j])){
wordNotFound=true
break;
}
else wordNotFound=true;
}
//// here i need the to change particular word back color not entire ritchtextbox
if (wordNotFound) richTextBox1.BackColor = Color.Red;
else richTextBox1.BackColor = Color.Green;
im not comparing two text boxes im validating each word which is exist in both side or not. just like spell check taking dictionary as one richtextbox1. spell check [valid word] in richtextbox2. vice versa...
var validWords = new HashSet<string>(new string[] { "a","c","e" });
string[] wordsToCheck = new string[] { "a", "b", "c", "d", "e" };
var result = wordsToCheck.Select(w => new
{
Word = w,
IsValid = validWords.Contains(w)
})
.ToList();
If you are only interested in whether all words are valid or not, you can simple check it by
var isOK = wordsToCheck.All(w => validWords.Contains(w));
PS: Of course, new string[]{}s should be replaced with rtb.Split(....) *
If the words would be in the same order why bother with splitting at all?
If it will be ok, I'd do:
if (richtexbox1.text.equals(richtexbox1.text)){
richTextBox1.BackColor = Color.Green;
} else {
richTextBox1.BackColor = Color.Red;
}
If not, and you want to find if both text boxes contain same word but in different order then:
String[] test = richtextbox1.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
String[] test2 = richtextbox2.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
bool wordNotFound=false;
for (int i=0;i<test.lenght;i++)
for (int j=0;j<test2.length;j++){
if (test[i].equals(test2[j])){
wordNotFound=false;
break;
}
else wordNotFound=true;
}
if (wordNotFound) richTextBox1.BackColor = Color.Red;
else richTextBox1.BackColor = Color.Green;
String[] test = richtextbox1.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
String[] test2 = richtextbox2.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
is giving error;
Error 1 The best overloaded method match for 'string.Split(string[],
System.StringSplitOptions)' has some invalid
arguments C:\Users\Saad\Documents\Visual Studio
2012\Projects\WindowsFormsApplication5\WindowsFormsApplication5\Form1.cs 60 29 WindowsFormsApplication5
Error 2 Argument 1: cannot convert from 'string' to
'string[]' C:\Users\Saad\Documents\Visual Studio
2012\Projects\WindowsFormsApplication5\WindowsFormsApplication5\Form1.cs 60 53 WindowsFormsApplication5
You could compare each word in textbox1 with textbox2
for(int i = 0; i < stringarray1.length; i++)
{
for(int j = 0; j < stringarray2.length; j++)
{
if(stringarray1[i] == stringarray2[j])
// we have a match
}
}

Bullet points in Word with c# Interop

I have the following code which is supposed to add a bulleted list to a word document that I'm generating automatically. From other answers I believe the code is correct, but the result doesn't produce any bullet points at all, it doesn't seem to apply the indent either.
Any Ideas?
Microsoft.Office.Interop.Word.Paragraph assets;
assets = doc.Content.Paragraphs.Add(Type.Missing);
// Some code to generate the text
foreach (String asset in assetsList)
{
assetText = assetText + asset + "\n";
}
assets.Range.ListFormat.ApplyBulletDefault(Type.Missing);
// Add it to the document
assets.Range.ParagraphFormat.LeftIndent = -1;
assets.Range.Text = assetText;
assets.Range.InsertParagraphAfter();
This happens because you're adding multiple paragraphs to the range after the range (it seems that setting the Text property is equivalent to InsertAfter). You want to InsertBefore the range so that the formatting you set gets applied.
Paragraph assets = doc.Content.Paragraphs.Add();
assets.Range.ListFormat.ApplyBulletDefault();
string[] bulletItems = new string[] { "One", "Two", "Three" };
for (int i = 0; i < bulletItems.Length; i++)
{
string bulletItem = bulletItems[i];
if (i < bulletItems.Length - 1)
bulletItem = bulletItem + "\n";
assets.Range.InsertBefore(bulletItem);
}
Notice that we add an End of Paragraph mark to all items except the last one. You will get an empty bullet if you add one to the last.
This is based on Tergiver's answer. The difference is it inserts the list items in the correct order after the initially created paragraph. For your own use make the starting range equal to the item you want to insert the list after.
Paragraph assets = doc.Content.Paragraphs.Add();
rng = assets.Range;
rng.InsertAfter("\n");
start = rng.End;
end = rng.End;
rng = _oDoc.Range(ref start, ref end);
object listType = 0;
rng.ListFormat.ApplyBulletDefault(ref listType);
string[] bulletItems = new string[] { "One", "Two", "Three" };
for (int i = 0; i < bulletItems.Length; i++)
{
string bulletItem = bulletItems[i];
if (i < RowCount - 1)
bulletItem = bulletItem + "\n";
rng.InsertAfter(bulletItem);
}
Please note I don't really understand what I'm doing with the range here. This solution was arrived at after considerable trial and error. I suspect it may have to do with the fact that I'm reusing the same range and Tergiver's solution is grabbing a new range each time the range is accessed. I particularly don't understand the following lines:
rng.InsertAfter("\n");
start = rng.End;
end = rng.End;
rng = _oDoc.Range(ref start, ref end);
Generally any alterations to the above code and the list gets intermingled with the previous element. If somebody could explain why this works, I'd be grateful.
You can try below code block if you want list-sublist relations:
static void Main(string[] args)
{
try
{
Application app = new Application();
Document doc = app.Documents.Add();
Range range = doc.Range(0, 0);
range.ListFormat.ApplyNumberDefault();
range.Text = "Birinci";
range.InsertParagraphAfter();
ListTemplate listTemplate = range.ListFormat.ListTemplate;
//range.InsertAfter("Birinci");
//range.InsertParagraphAfter();
//range.InsertAfter("İkinci");
//range.InsertParagraphAfter();
//range.InsertAfter("Üçüncü");
//range.InsertParagraphAfter();
Range subRange = doc.Range(range.StoryLength - 1);
subRange.ListFormat.ApplyBulletDefault();
subRange.ListFormat.ListIndent();
subRange.Text = "Alt Birinci";
subRange.InsertParagraphAfter();
ListTemplate sublistTemplate = subRange.ListFormat.ListTemplate;
Range subRange2 = doc.Range(subRange.StoryLength - 1);
subRange2.ListFormat.ApplyListTemplate(sublistTemplate);
subRange2.ListFormat.ListIndent();
subRange2.Text = "Alt İkinci";
subRange2.InsertParagraphAfter();
Range range2 = doc.Range(range.StoryLength - 1);
range2.ListFormat.ApplyListTemplateWithLevel(listTemplate,true);
WdContinue isContinue = range2.ListFormat.CanContinuePreviousList(listTemplate);
range2.Text = "İkinci";
range2.InsertParagraphAfter();
Range range3 = doc.Range(range2.StoryLength - 1);
range3.ListFormat.ApplyListTemplate(listTemplate);
range3.Text = "Üçüncü";
range3.InsertParagraphAfter();
string path = Environment.CurrentDirectory;
int totalExistDocx = Directory.GetFiles(path, "test*.docx").Count();
path = Path.Combine(path, string.Format("test{0}.docx", totalExistDocx + 1));
app.ActiveDocument.SaveAs2(path, WdSaveFormat.wdFormatXMLDocument);
doc.Close();
Process.Start(path);
}
catch (Exception exception)
{
throw;
}
}
Attention this point: If you don't know input length, you must not define the end of range value like this:
static void Main(string[] args)
{
try
{
Application app = new Application();
Document doc = app.Documents.Add();
Range range = doc.Range(0, 0);
range.ListFormat.ApplyNumberDefault();
range.Text = "Birinci";
range.InsertParagraphAfter();
ListTemplate listTemplate = range.ListFormat.ListTemplate;
//range.InsertAfter("Birinci");
//range.InsertParagraphAfter();
//range.InsertAfter("İkinci");
//range.InsertParagraphAfter();
//range.InsertAfter("Üçüncü");
//range.InsertParagraphAfter();
Range subRange = doc.Range(range.StoryLength - 1, range.StoryLength - 1);
subRange.ListFormat.ApplyBulletDefault();
subRange.ListFormat.ListIndent();
subRange.Text = "Alt Birinci";
subRange.InsertParagraphAfter();
ListTemplate sublistTemplate = subRange.ListFormat.ListTemplate;
Range subRange2 = doc.Range(subRange.StoryLength - 1, range.StoryLength - 1);
subRange2.ListFormat.ApplyListTemplate(sublistTemplate);
subRange2.ListFormat.ListIndent();
subRange2.Text = "Alt İkinci";
subRange2.InsertParagraphAfter();
Range range2 = doc.Range(range.StoryLength - 1, range.StoryLength - 1);
range2.ListFormat.ApplyListTemplateWithLevel(listTemplate,true);
WdContinue isContinue = range2.ListFormat.CanContinuePreviousList(listTemplate);
range2.Text = "İkinci";
range2.InsertParagraphAfter();
Range range3 = doc.Range(range2.StoryLength - 1, range.StoryLength - 1);
range3.ListFormat.ApplyListTemplate(listTemplate);
range3.Text = "Üçüncü";
range3.InsertParagraphAfter();
string path = Environment.CurrentDirectory;
int totalExistDocx = Directory.GetFiles(path, "test*.docx").Count();
path = Path.Combine(path, string.Format("test{0}.docx", totalExistDocx + 1));
app.ActiveDocument.SaveAs2(path, WdSaveFormat.wdFormatXMLDocument);
doc.Close();
Process.Start(path);
}
catch (Exception exception)
{
throw;
}
}
You just need to keep track of the start and end positions of the list and then apply the list format.
Application wordApp = new Application() {
Visible = true
};
Document doc = wordApp.Documents.Add();
Range range = doc.Content;
range.Text = "Hello world!";
range.InsertParagraphAfter();
range = doc.Paragraphs.Last.Range;
// start of list
int startOfList = range.Start;
// each \n character adds a new paragraph...
range.Text = "Item 1\nItem 2\nItem 3";
// ...or insert a new paragraph...
range.InsertParagraphAfter();
range = doc.Paragraphs.Last.Range;
range.Text = "Item 4\nItem 5";
// end of list
int endOfList = range.End;
// insert the next paragraph before applying the format, otherwise
// the format will be copied to the suceeding paragraphs.
range.InsertParagraphAfter();
// apply list format
Range listRange = doc.Range(startOfList, endOfList);
listRange.ListFormat.ApplyBulletDefault();
range = doc.Paragraphs.Last.Range;
range.Text = "Bye for now!";
range.InsertParagraphAfter();

Categories